I have a trigger on a master-detail object where Doctor is master and Patient is child. Doctor has a field called TotalAmount and Patient has a field called Amount. Now, when a patient is filling in the amount field, the TotalAmount field in Doctor should give the sum of Amount in all the patient records.
I have written the code below, but it shows an error:
Invalid identifier: Amount__c
How can I fix this?
trigger tgPatient on Patient__c (after insert,after update) {
Set<Id>SetDoctor = new Set<Id>();
for (Patient__c p : trigger.new) {
if( p.Amount__c != Null ) {
SetDoctor.add(p.Doctor__c);
}
}
List<Doctor> lstDoctor = new List<Doctor>();
for( Doctor__c d : [SELECT Id, (SELECT Id,Amount__c FROM Patients__r) FROM Doctor__c WHERE Id IN:SetDoctor]){
Integer Amount__c = 0;
for (Patient__c p : d.Patient__r) {
int Amount__c += p.Amount__c;
}
d.Total_Amount__c = int Amount__c;
lstDoctor.add(d);
}
update lstDoctor;
}
Try the below one:
trigger tgPatient on Patient__c (after insert,after update) {
Set<Id>SetDoctor = new Set<Id>();
for (Patient__c p : trigger.new){
if( p.Amount__c != Null ){
SetDoctor.add(p.Doctor__c);
}
}
List<Doctor> lstDoctor = new List<Doctor>();
for( Doctor__c d : [SELECT Id, (SELECT Id,Amount__c FROM Patients__r) FROM Doctor__c WHERE Id IN:SetDoctor]){
Integer amountVAR = 0;
for (Patient__c p : d.Patient__r){
amountVAR += p.Amount__c;
}
d.Total_Amount__c = amountVAR ;
lstDoctor.add(d);
}
update lstDoctor;
regards
ajay
Try below:
trigger tgPatient on Patient__c(after insert, after update) {
Set < Id > SetDoctor = new Set < Id > ();
for (Patient__c p: trigger.new) {
if (p.Amount__c != Null) {
SetDoctor.add(p.Doctor__c);
}
}
List < Doctor > lstDoctor = new List < Doctor > ();
for (Doctor__c d: [SELECT Id, (SELECT Id, Amount__c FROM Patients__r) FROM Doctor__c WHERE Id IN: SetDoctor]) {
d.Total_Amount__c = 0;
for (Patient__c p: d.Patient__r) {
d.Total_Amount__c += p.Amount__c;
}
lstDoctor.add(d);
}
update lstDoctor;
}
But why do you want to use a Trigger? Why not create a roll-up summary field on Doctor?
Creating Roll Up Summary fields
Related
**When I run the below test class it return empty list in query method. I there any different way to write test class for aggregate batch apex **
global class Batch_Agent implements Database.Batchable {
global Iterable<AggregateResult> start(Database.BatchableContext BC){
string query='SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, SUM(Monthly_Premium__c) Sum_of_Monthly_Permium ,Sales_Agent__c FROM InsurancePolicy WHERE Is_Agency_commission_Paid__c=False and Effectuated__c=true and Submitted_Date__c >= 2021-02-02 and Submitted_Date__c <= 2021-05-01 and Sales_Agent__r.Sales_Agent_User__r.IsActive = true and Expected_Agency_Commission__c!= 0 and Expected_Agency_Commission__c!= null Group by Sales_Agent__c, Is_Agency_commission_Paid__c ';
return new AggregateResultIterable(query);
}
global void execute(Database.BatchableContext BC, List<Sobject> scope){
List<Sobject> policyLists = scope;
List<contact> agentContactList = new List<contact>();
List<Contact> conlist = [SELECT Id, Name, Seat_Cost__c, Tier__c FROM Contact WHERE Sales_Agent_User__r.IsActive = true and RecordType.name ='Sales Agent'];
List<Bonus_Amount__c> bonusList = [SELECT Id , Name, Commission_Amount__c,Commission_End_Amount__c,Bonus_Percentage__c FROM Bonus_Amount__c ];
List<Agent_Commission__c> agentComList = new List<Agent_Commission__c>();
list<Id> salesAgentIds = new List<Id>();
for(Sobject policy:policyLists){
if(policy.Get('Sales_Agent__c')!=null){
Id conIds;
Decimal seatCost;
String agentTier;
Decimal comissionAmount;
Decimal bonusPercentage;
Agent_Commission__c agentComm = new Agent_Commission__c();
agentComm.Sum_of_Expected_Agency_Commission__c = (Decimal)policy.Get('Sum_of_Agency_Commission');
agentComm.Sum_of_Monthly_Permium__c = (Decimal)policy.Get('Sum_of_Monthly_Permium');
conIds = (Id)policy.Get('Sales_Agent__c');
for(contact con:conlist ){
if(con.Id==conIds){
seatCost=con.Seat_Cost__c;
agentTier=con.Tier__c;
}
}
agentComm.Commisionable_Amount__c = ((Decimal)policy.Get('Sum_of_Agency_Commission')-seatCost);
comissionAmount = agentComm.Commisionable_Amount__c ;
for(Bonus_Amount__c bnus:bonusList){
if(bnus.Name == agentTier){
if (comissionAmount < 0 ){
bonusPercentage = 0;
}
else if( comissionAmount >= bnus.Commission_Amount__c && comissionAmount < bnus.Commission_End_Amount__c){
bonusPercentage = bnus.Bonus_Percentage__c;
}
}
}
agentComm.Bonus_Percentage__c = bonusPercentage;
agentComm.Bonus_Amount__c = comissionAmount*bonusPercentage;
agentComm.Sales_Agent__c = (String)policy.Get('Sales_Agent__c');
salesAgentIds.add(agentComm.Sales_Agent__c);
agentComm.Name = String.valueOf(System.now());
agentComList.add(agentComm);
}
}
Insert agentComList;
List<InsurancePolicy> policyUpdates = [SELECT ID, Name, test_Is_Agency_commission_Paid__c, Is_Agency_commission_Paid__c, Sales_Agent__c FROM InsurancePolicy
WHERE Is_Agency_commission_Paid__c= false and Sales_Agent__r.Sales_Agent_User__r.IsActive = true and
Expected_Agency_Commission__c!= 0 and Expected_Agency_Commission__c!= null and Effectuated__c=true and
Submitted_Date__c > 2021-01-01 and Sales_Agent__c in :salesAgentIDs ];
for(InsurancePolicy polupdate :policyUpdates ){
polupdate.Is_Agency_commission_Paid__c = false;
}
Update policyUpdates;
}
global void finish(Database.BatchableContext BC){
}
}
==================================================
#isTest(SeeAllData = FALSE)
public class lig_AgentCommissionTrigerHandlerTest {
private static Contact createContact(String lastName, Boolean withInsert ){
Contact newContact = new Contact(
LastName = lastName,
recordTypeId = Schema.getGlobalDescribe().get('Contact').getDescribe().getRecordTypeInfosByName().get('Sales Agent').getRecordTypeId(),
Seat_Cost__c = 22000,
Tier__c = 'T1'
);
if(withInsert){
insert newContact;
}
return newContact;
}
private static Bonus_Amount__c createBonusList(Boolean withInsert){
Bonus_Amount__c newBonusAmount = new Bonus_Amount__c(
Name = 'T1',
Commission_Amount__c = 2100,
Commission_End_Amount__c = 3500,
Bonus_Percentage__c = 0.03
);
if(withInsert){
insert newBonusAmount ;
}
return newBonusAmount ;
}
private static InsurancePolicy createInsurancePolicy(String name, Id nameInsuredId, Id saleAgentID,Integer agencycom, Integer mnthlyper, Boolean withInsert){
InsurancePolicy newPolicy = new InsurancePolicy(
NameInsuredId = nameInsuredId,
Name = name,
Sales_Agent__c = saleAgentID,
Expected_Agency_Commission__c = 12345,
Monthly_Premium__c = 231,
Is_Agency_commission_Paid__c = False
//Effectuated__c = True
);
if(withInsert){
insert newPolicy;
}
return newPolicy;
}
#TestSetup
private static void createTestData() {
//create test account
//create test account
Account policyHolder = lig_TestDataFactory.createPersonAccount('Test',
'Account',
'test#account.com',
'1234567890',
'1234567980',
TRUE);
Contact agentContact = lig_AgentCommissionTrigerHandlerTest.createContact('Test',
TRUE);
Bonus_Amount__c bonusAmount = lig_AgentCommissionTrigerHandlerTest.createBonusList(TRUE);
List<InsurancePolicy> testPolicies = new List<InsurancePolicy>();
testPolicies.add(lig_AgentCommissionTrigerHandlerTest.createInsurancePolicy('Test Policy 1',
policyHolder.Id,
agentContact.Id,
1234,
212,
FALSE));
testPolicies.add(lig_AgentCommissionTrigerHandlerTest.createInsurancePolicy('Test Policy 2',
policyHolder.Id,
agentContact.Id,
2311,
123,
FALSE));
insert testPolicies;
}
#isTest static void testCreateRenewalOppty()
{
List<Sobject> policies = [SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, SUM(Monthly_Premium__c) Sum_of_Monthly_Permium ,Sales_Agent__c FROM InsurancePolicy
WHERE Is_Agency_commission_Paid__c=False Group by Sales_Agent__c];
List<Bonus_Amount__c> bonusList = [SELECT Id , Name, Commission_Amount__c,Commission_End_Amount__c,Bonus_Percentage__c FROM Bonus_Amount__c ];
list<Id> salesAgentIds = new List<Id>();
Test.startTest();
Batch_Agent baAgent = new Batch_Agent();
ID jobID = database.executebatch(baAgent,5);
Test.stopTest();
}
}
It returns an empty list because the test data you are creating does not match the query filters:
SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission,
SUM(Monthly_Premium__c) Sum_of_Monthly_Permium,
Sales_Agent__c
FROM InsurancePolicy
WHERE Is_Agency_commission_Paid__c=False
and Effectuated__c=true
and Submitted_Date__c >= 2021-02-02
and Submitted_Date__c <= 2021-05-01
and Sales_Agent__r.Sales_Agent_User__r.IsActive = true
and Expected_Agency_Commission__c!= 0
and Expected_Agency_Commission__c!= null
Group by Sales_Agent__c, Is_Agency_commission_Paid__c
Your test-context InsurancePolicy records must match all of the WHERE filters. Note as one example that your test data factory doesn't populate the Submitted_Date__c field. (It's unclear why you have hard-coded these values in your query).
I cannot resolve this error.
Closing a Maintenance Request of type 'Routine Maintenance' or 'Repair' did not create of a new Maintenance Request with the correct due date. The challenge is expecting the due date to be calculated using the maintenance cycle defined on the related equipment records. If multiple equipments are used in the maintenance request, choose the shortest maintenance cycle to define the service date.
I'm having a really hard time finishing this challenge. I want to know that which part of my code is wrong, not just answer.
// TriggerHandler
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(Map<Id, Case> oldCases) {
// TODO: Complete the method to update workorders
Map<Id, Integer> toGetDueDateMap = new Map<Id, Integer>();
AggregateResult[] results = [SELECT Id, MIN(Maintenance_Cycle__c) minMC FROM Product2 GROUP BY Id];
for (AggregateResult ar : results) {
if (ar != null) {
toGetDueDateMap.put(ar.Id, Integer.valueOf(ar.get('minMC')));
}
}
List<Case> newCases = new List<Case>();
for (Case c : oldCases.values()) {
Case newCase = new Case();
newCase.Status = 'New';
newCase.Origin = 'web';
newCase.Vehicle__c = c.Vehicle__c;
newCase.ProductId = c.ProductId;
newCase.Type = 'Routine Maintenance';
newCase.Subject = 'Routine Maintenance';
newCase.Date_Reported__c = Date.today();
newCase.Date_Due__c = (toGetDueDateMap.get(c.Id) != null) ? Date.today().addDays(toGetDueDateMap.get(c.Id)) : Date.today();
newCases.add(newCase);
}
insert newCases;
}
}
// Trigger
trigger MaintenanceRequest on Case (after update) {
// ToDo: Call MaintenanceRequestHelper.updateWorkOrders
Map<Id, Case> caseToEvaluate = new Map<Id, Case>();
if(Trigger.isAfter && Trigger.isUpdate) {
for(Case c : Trigger.New) {
if(c.Status == 'Closed' && (c.Type == 'Repair' || c.Type == 'Routine Maintenance')) {
caseToEvaluate.put(c.Id, c);
}
}
}
MaintenanceRequestHelper.updateWorkOrders(caseToEvaluate);
}
I create correct algoritm to find less maintenance cycle days.
Try it.
newCase.Date_Due__c = Date.today() + suchEarlyDay(newMaintenanceRequest).get(cases.Id);
newCases.add(newCase);
}
}
if (newCases.size() > 0) {
insert newCases;
}
}
private static Map<Id, Integer> suchEarlyDay(List<Case> cases) {
Map<Id, Case> caseMap = new Map<Id, Case>(cases);
Map<Id, Integer> lessDate = new Map<Id, Integer>();
List<Equipment_Maintenance_Item__c> relatedList = [
SELECT Maintenance_Request__c,
Equipment__r.Maintenance_Cycle__c
FROM Equipment_Maintenance_Item__c
WHERE Maintenance_Request__c = :caseMap.keySet()
];
for (Id caseId : caseMap.keySet()) {
for (Equipment_Maintenance_Item__c equip : relatedList) {
if (!lessDate.containsKey(caseId) && caseId == equip.Maintenance_Request__c) {
lessDate.put(caseId, (Integer) equip.Equipment__r.Maintenance_Cycle__c);
} else if (lessDate.containsKey(caseId) && lessDate.get(caseId) > (Integer) equip.Equipment__r.Maintenance_Cycle__c) {
lessDate.put(caseId, (Integer) equip.Equipment__r.Maintenance_Cycle__c);
}
}
}
return lessDate;
}
This link helped me, so I modified the code like this:
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<Case> updWorkOrders, Map<Id,Case> nonUpdCaseMap) {
Set<Id> validIds = new Set<Id>();
For (Case c : updWorkOrders){
if (nonUpdCaseMap.get(c.Id).Status != 'Closed' && c.Status == 'Closed'){
if (c.Type == 'Repair' || c.Type == 'Routine Maintenance'){
validIds.add(c.Id);
}
}
}
if (!validIds.isEmpty()){
List<Case> newCases = new List<Case>();
Map<Id,Case> closedCasesM = new Map<Id,Case>([SELECT Id, Vehicle__c, ProductId, Product.Maintenance_Cycle__c,(SELECT Id,Equipment__c,Quantity__c FROM Equipment_Maintenance_Items__r)
FROM Case WHERE Id IN :validIds]);
Map<Id,Decimal> maintenanceCycles = new Map<ID,Decimal>();
AggregateResult[] results = [SELECT Maintenance_Request__c, MIN(Equipment__r.Maintenance_Cycle__c)cycle FROM Equipment_Maintenance_Item__c WHERE Maintenance_Request__c IN :ValidIds GROUP BY Maintenance_Request__c];
for (AggregateResult ar : results){
maintenanceCycles.put((Id) ar.get('Maintenance_Request__c'), (Decimal) ar.get('cycle'));
}
for(Case cc : closedCasesM.values()){
Case nc = new Case (
ParentId = cc.Id,
Status = 'New',
Subject = 'Routine Maintenance',
Type = 'Routine Maintenance',
Vehicle__c = cc.Vehicle__c,
ProductId =cc.ProductId,
Origin = 'Web',
Date_Reported__c = Date.Today()
);
If (maintenanceCycles.containskey(cc.Id)){
nc.Date_Due__c = Date.today().addDays((Integer) maintenanceCycles.get(cc.Id));
} else {
nc.Date_Due__c = Date.today().addDays((Integer) cc.Product.maintenance_Cycle__c);
}
newCases.add(nc);
}
insert newCases;
List<Equipment_Maintenance_Item__c> clonedWPs = new List<Equipment_Maintenance_Item__c>();
for (Case nc : newCases){
for (Equipment_Maintenance_Item__c wp : closedCasesM.get(nc.ParentId).Equipment_Maintenance_Items__r){
Equipment_Maintenance_Item__c wpClone = wp.clone();
wpClone.Maintenance_Request__c = nc.Id;
ClonedWPs.add(wpClone);
}
}
insert ClonedWPs;
}
}
}
And the trigger:
trigger MaintenanceRequest on Case (before update, after update) {
if(Trigger.isUpdate && Trigger.isAfter){
MaintenanceRequestHelper.updateWorkOrders(Trigger.New, Trigger.OldMap);
} }
Apex Trigger :
trigger MaintenanceRequest on Case (before update, after update) {
// ToDo: Call MaintenanceRequestHelper.updateWorkOrders
if(Trigger.isAfter && Trigger.isUpdate){
MaintenanceRequestHelper.updateWorkOrders(Trigger.new);
}
}
Apex Handler:
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<Case> existingMainReq) {
// TODO: Complete the method to update workorders
Integer count = 0;
Map<Id, Integer> toGetDueDateMap = new Map<Id, Integer>();
Map<Id,Case> newCasesToIdsMap = new Map<Id,Case>();
List<Case> createNewMainReq = new List<Case>();
List<Case> caseIdsList = new List<Case>();
Map<Equipment_Maintenance_Item__c,Id> EquipMainItemsToProdIds = new Map<Equipment_Maintenance_Item__c,Id>();
if(!existingMainReq.isEmpty()){
for(Case cc : existingMainReq){
if((cc.Type == 'Repair' || cc.Type == 'Routine Maintenance') && cc.Status == 'Closed'){
caseIdsList.add(cc);
}
}
}
List<Equipment_Maintenance_Item__c> equipMainList = [Select id,Equipment__c,Maintenance_Request__c from Equipment_Maintenance_Item__c where Maintenance_Request__c IN : caseIdsList];
if(!equipMainList.isEmpty()){
for(Equipment_Maintenance_Item__c equipMainn : equipMainList){
EquipMainItemsToProdIds.put(equipMainn,equipMainn.Equipment__c);
system.debug(EquipMainItemsToProdIds.size());
if(EquipMainItemsToProdIds.size() > 1){
count = EquipMainItemsToProdIds.size();
}
}
}
List<Equipment_Maintenance_Item__c> EMIList = [Select Equipment__r.Maintenance_Cycle__c,Equipment__c from Equipment_Maintenance_Item__c where Equipment__r.Id IN :EquipMainItemsToProdIds.values() AND Maintenance_Request__c IN:caseIdsList order By Equipment__r.Maintenance_Cycle__c ASC limit 1];
for(Equipment_Maintenance_Item__c equip : EMIList){
toGetDueDateMap.put(equip.Id,Integer.valueOf(equip.Equipment__r.Maintenance_Cycle__c));
for(Case c : caseIdsList){
Case mainRe = new Case();
mainRe.Vehicle__c = c.Vehicle__c;
mainRe.status = 'New';
mainRe.Type = 'Routine Maintenance';
mainRe.Subject = 'New Main Request For Vehicle for Apex Specialist';
mainRe.Date_Reported__c = date.today();
if(count > 1){
mainRe.Date_Due__c = Date.today().addDays(toGetDueDateMap.get(equip.Id));
}
else{
mainRe.Date_Due__c = Date.today();
}
createNewMainReq.add(mainRe);
newCasesToIdsMap.put(c.Id,mainRe);
}
insert createNewMainReq;
if(caseIdsList.size()>0 && newCasesToIdsMap.size()>0){
cloneEquipItems(caseIdsList,newCasesToIdsMap);
}
}
}
public static void cloneEquipItems(List<case> closedCaseRecords, Map<Id,case> newCreatedCasesMapp){
List<Equipment_Maintenance_Item__c> newEquipItems = new List<Equipment_Maintenance_Item__c>();
try{
if(!closedCaseRecords.isEmpty() && newCreatedCasesMapp.size()>0){
List<Equipment_Maintenance_Item__c> oldEquipItems = [SELECT Equipment__c, Maintenance_Request__c, Quantity__c,Maintenance_Request__r.Id
FROM Equipment_Maintenance_Item__c
WHERE Maintenance_Request__c IN :closedCaseRecords];
for(Equipment_Maintenance_Item__c equipItem : oldEquipItems) {
Equipment_Maintenance_Item__c newItem = equipItem.clone(false, true, false, false);
newItem.Maintenance_Request__c = newCreatedCasesMapp.get(equipItem.Maintenance_Request__c).id;
newEquipItems.add(newItem);
}
insert newEquipItems;
}
}
catch(Exception e){
System.debug('Exception is'+ e);
}
}
}
I have a table in which i have three columns ( id,studentid,courseid) in my model class i have studentid and courseid as arrays as on view they are multi select dropdownlist , Now in my create controller i want to loop through the student first and then asssign all courses which comes in courses array and then after assigning all course i need to move to next student and assign him all course
public ActionResult Create([Bind(Include = "Id,Year_Id,Program_Id,Student_id,Module_Id,Course_Id")]Student_Assigned_courses SAC)
{
ViewBag.PopulatePrograms = _IEducation.PopulatePrograms();
//ViewBag.Block_Id = new SelectList(db.Blocks, "Id", "Name");
//ViewBag.Course_Category_Id = new SelectList(db.Courses_Category, "Id", "Category_Name");
//ViewBag.Module_Id = new SelectList(db.Moduels, "Id", "Name");
//ViewBag.Program_Id = new SelectList(db.Programs, "Id", "Program_Title");
//ViewBag.Year = new SelectList(db.Years, "Id", "Name");
//ViewBag.Course_Id = _ITeacherCoruses.PopulateCourses();
//ViewBag.Teacher_Id = _ITeacherCoruses.PopulateTeachers();
//ViewBag.Semester_Id = _ITeacherCoruses.PopulateSemsters();
if (SAC.Student_id != null)
{
foreach(var student in SAC.Student_id)
{
for (int i = 0; i < SAC.Course_Id.Length; i++)
// SAC.Course_Id = SAC.Course_Id[i] ;
db.StudentCoursesAssigned.Add(SAC);
if (db.SaveChanges() > 0)
{
TempData["MessageDesignation"] = "Department Saved Successfully!";
}
}
return RedirectToAction("Index");
}
return View(SAC);
}
I gave just three columns but in reality i have five columns in my table and model class .
I'm creating OrderItem records and getting error, cross reference identity:
Reason -nsert failed. First exception on row 1; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id:
Any help with this reference?
public class OrderItemCreate {
public static void createOrderLine() {
List<PriceBookEntry> priceBookList = new List<PriceBookEntry> ([SELECT Id, Pricebook2Id FROM PriceBookEntry]);
Set<Id> priceBookSet = new Set<Id>();
for (PriceBookEntry pb: priceBookList) {
priceBookSet.add(pb.Pricebook2Id);
}
List<OrderItem> orderItemList = new List<OrderItem>();
List<Order> orderList = new List< Order>([SELECT id FROM Order WHERE PriceBook2Id IN: priceBookSet]);
for (Integer i = 1; i <= 5; i++) {
OrderItem temp = new OrderItem();
temp.PricebookEntryId = priceBookList.get(Math.mod(i, 2)).id;
temp.OrderId = orderList.get(Math.mod(i, 2)).Id;
temp.UnitPrice = 100;
temp.Quantity = 1;
orderItemList.add(temp);
}
if (orderItemList.size() > 0)
insert orderItemList;
}
}
This line :
temp.PricebookEntryId = priceBookList.get(Math.mod(i, 2)).id;
should be :
temp.PricebookEntryId = priceBookSet.get(Math.mod(i, 2)).id;
You were trying to put a PriceBookEntry id into a PriceBookId field.
I suggest you rename your variable PriceBookList to PriceBookEntryList.
This is my method :-
[Invoke]
public List<FamilyEvent> GetFamilyEvents(int userId)
{
List<FamilyEvent> familyEvents = new List<FamilyEvent>();
int id = -1; //just to fool ria
//this is for birthday reminders.
var qry = ((from member in this.ObjectContext.TreeMembers.Where(m => m.UserId == userId && m.Birthdate == null)
select member.TreeMemberId).Except(from item in this.ObjectContext.FamilyEvents where item.ReminderType ==
FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.BIRTHDAY_REMINDER
select item.TreeMemberId));
var mainQry = from mainMember in this.ObjectContext.TreeMembers
where qry.Contains(mainMember.TreeMemberId)
select mainMember;
foreach (var item in mainQry)
{
FamilyEvent familyEvent = new FamilyEvent
{
FamilyEventId = id--,
TreeMemberId = item.TreeMemberId,
RelatedTreeMemberId = -1,
ReminderType = FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.BIRTHDAY_REMINDER
};
familyEvent.TreeMember = item;
familyEvents.Add(familyEvent);
}
//this is for anniversary events
qry = ((from member in this.ObjectContext.TreeMembers.Where(m => m.UserId == userId && m.RelationId == (short)Relations.Partner)
select member.TreeMemberId).Except(from item in this.ObjectContext.FamilyEvents where item.ReminderType == FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.ANNIVERSARY_REMINDER
select item.TreeMemberId));
mainQry = from mainMember in this.ObjectContext.TreeMembers.Include("RelatedTreeMember")
where qry.Contains(mainMember.TreeMemberId)
select mainMember;
foreach (var item in mainQry)
{
FamilyEvent familyEvent = new FamilyEvent
{
TreeMemberId = item.TreeMemberId,
TreeMember = item,
RelatedTreeMemberId = item.RelatedTreeMemberId,
ReminderType = FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.ANNIVERSARY_REMINDER
};
familyEvent.RelatedTreeMember = item.RelatedTreeMember;
familyEvents.Add(familyEvent);
}
return familyEvents;
}
As you can see i programmatically populate the entities and populate it. When i put breakpoint on return familyEvents, i can see the correct data. However on client side, the TreeMember and RelatedTreeMember value become null. Why is it so? If i do not use [Invoke] and instead use [Query] it works, but i need Invoke in my case.