I have this error :
LINQ to Entities does not recognize the method: GetDebitOuCredit
When I run this:
using (SXEntities db = new SXEntities())
{
result = from ecriture in db.Ecrits
join compte in db.Comptes on ecriture.Compte equals compte.Compte1
join societe in db.Societes on ecriture.Societe equals societe.Societe1
select new EcritDTO
{
LibelleElement = compte.Libelle,
LienGED = string.Empty, // WIP
Compte = ecriture.Compte,
Collectif = ecriture.RacColtif,
Date = ecriture.DateC,
Journal = ecriture.Journal,
Piece = ecriture.Piece,
CodeOperation = ecriture.CodeOpe,
Libelle = ecriture.Libelle,
ReferenceDocument = ecriture.DocuRef,
// Error just below
Debit = GetDebitOuCredit("Debit", societe.DCMoins, ecriture.MtDeb, ecriture.MtCre),
};
}
I cannot use this function:
public double GetDebitOuCredit(string choix, string dcMoins, double? montantDebit, double? montantCredit)
{
double debit = 0;
double credit = 0;
bool isMontantNegatif = string.IsNullOrEmpty(dcMoins) && dcMoins == "1";
if(montantDebit != null && montantDebit != 0 && montantCredit != null && montantCredit != 0)
{
double difference = (double)montantDebit - (double)montantCredit;
if(difference < 0 && isMontantNegatif)
{
debit = 0;
credit = Math.Abs(difference);
}
else
{
debit = difference;
credit = 0;
}
}
return choix == "Debit" ? debit : credit;
}
My question: How can I transform my function GetDebitOrCredit to LINQ expression?
Actually if it is final projection, you don't have to translate this function.
If not, you have to use third party extensions for that:
https://github.com/hazzik/DelegateDecompiler
https://github.com/axelheer/nein-linq/
Never tried DelegateDecompiler, so will show sample using NeinLinq
[InjectLambda]
public double GetDebitOuCredit(string choix, string dcMoins, double? montantDebit, double? montantCredit)
{
_getDebitOuCreditFunc ??= GetDebitOuCredit().Compile();
return _getDebitOuCreditFunc(choix, dcMoins, montantDebit, montantCredit);
}
static Func<string, string, double?, double?, double> _getDebitOuCreditFunc;
public static Expression<Func<string, string, double?, double?, double>> GetDebitOuCredit()
{
return (choix, dcMoins, montantDebit, montantCredit) =>
montantDebit != null && montantDebit != 0 && montantCredit != null && montantCredit != 0)
? ((double)montantDebit < (double)montantCredit) && dcMoins == "1"
? choix == "Debit" ? 0 : (double)montantCredit) - (double)montantDebit
: choix == "Debit" ? (double)montantDebit - (double)montantCredit) : 0
: 0;
}
Then you can use your function in LINQ queries after ToInjectable() call.
result = from ecriture in db.Ecrits.ToInjectable()
join compte in db.Comptes on ecriture.Compte equals compte.Compte1
...
Perhaps you forgot to actually run the query and it's running later when you try to apply some other operation to it. Try
using (SXEntities db = new SXEntities())
{
var q = from ecriture in db.Ecrits
join compte in db.Comptes on ecriture.Compte equals compte.Compte1
join societe in db.Societes on ecriture.Societe equals societe.Societe1
select new EcritDTO
{
LibelleElement = compte.Libelle,
LienGED = string.Empty, // WIP
Compte = ecriture.Compte,
Collectif = ecriture.RacColtif,
Date = ecriture.DateC,
Journal = ecriture.Journal,
Piece = ecriture.Piece,
CodeOperation = ecriture.CodeOpe,
Libelle = ecriture.Libelle,
ReferenceDocument = ecriture.DocuRef,
// Error just below
Debit = GetDebitOuCredit("Debit", societe.DCMoins, ecriture.MtDeb, ecriture.MtCre),
};
result = q.ToList();
}
Also you should be able to remove the joins and do something like:
using (SXEntities db = new SXEntities())
{
var q = from ecriture in db.Ecrits
select new EcritDTO
{
LibelleElement = ecriture.Compte.Libelle,
LienGED = string.Empty, // WIP
Compte = ecriture.Compte,
Collectif = ecriture.RacColtif,
Date = ecriture.DateC,
Journal = ecriture.Journal,
Piece = ecriture.Piece,
CodeOperation = ecriture.CodeOpe,
Libelle = ecriture.Libelle,
ReferenceDocument = ecriture.DocuRef,
// Error just below
Debit = GetDebitOuCredit("Debit", ecriture.Societe.DCMoins, ecriture.MtDeb, ecriture.MtCre),
};
result = q.ToList();
}
Assuming your model has proper navigation properties.
Related
Good Day To you all
I have issue with using 'predicate'
I'm trying to make function to return the results of some search text
here is the body of the function
public List<SaddadVM> GetAllBills(int Page = 1, int Take = 10, int? SearchField = null, string SearchItem = null)
{
var predicate = PredicateBuilder.New<SaddadVM>();
if (!string.IsNullOrWhiteSpace(SearchItem))
{
predicate = predicate.And(x => x.BillAcct == SearchItem);
}
predicate = predicate.And(x => x.Id != 0);
var bill = (from d in _context.Saddad
join R in _context.Requests on d.ReqId equals R.Id
join l in _context.Documenter on R.DocumenterId equals l.Id
where d.RecordStatus != GeneralEnums.RecordStatus.Deleted
select new SaddadVM
{
BillAcct = d.BillAcct,
ReqID = d.ReqId,
DocName = l.FullName,
DueDt = d.DueDt,
BillAmount = d.BillAmount
}).Where(predicate).Skip((Page - 1) * Take).Take(Take).ToList();
return bill;
}
Knowing that the the Bill object should return at least 2 depending on running the same query on DB as follows :
enter image description here
I want to assign GetMajorMileStone(projecttask.ProjectTaskId) result to MajorMilestone.
I tried but getting following error:
LINQ to Entities does not recognize the method
'System.Data.Objects.ObjectResult1[.Poco.GetMajorMileStone_Result]
GetMajorMileStone(System.Nullable1[System.Guid])' method, and this
method cannot be translated into a store expression.'
Here is my code:
public ProjectsPayload GetProjectSchedule(int projectid, bool includeArchived, DateTime startDate, DateTime endDate, int userId)
{
using (var db = new Entities())
{
try
{
db.CommandTimeout = 1200;
var query = from project in db.Project.Where(t => (t.Active || t.TempActive) && t.ProjectId == projectid)
join UP in db.User_X_Project on project.ProjectId equals UP.ProjectId
where (UP.UserId == userId && UP.Active)
orderby (project.Priority ?? int.MaxValue)
orderby (project.ProjectTitle)
select new
{
Project = project,
ProjectTask = from projecttask in project.ProjectTask.Where(t => t.Active && (
(includeArchived == true && t.TaskStatusId == (int?)TaskStatus.Archived) ||
(includeArchived == false && t.TaskStatusId != (int?)TaskStatus.Archived))
|| t.TaskStatusId != (int?)TaskStatus.Planned)
join schedule in project.ProjectTask.SelectMany(p => p.ProjectTaskSchedule) on projecttask.ProjectTaskId equals schedule.ProjectTaskId
join daily in db.ProjectTaskSchedule.SelectMany(p => p.DailyStatus) on schedule.ProjectTaskScheduleId equals daily.ProjectTaskScheduleId
where schedule.Active && daily.Active && projecttask.Active && schedule.ResourceId == userId && (
(EntityFunctions.TruncateTime(daily.Date) >= EntityFunctions.TruncateTime(startDate.Date) &&
EntityFunctions.TruncateTime(daily.Date) <= EntityFunctions.TruncateTime(endDate.Date))
)
orderby schedule.StartDate
select new
{
ProjectTask = projecttask,
ProjectTaskSchedule = from projecttaskschedule in projecttask.ProjectTaskSchedule.Where(t => t.Active && t.ResourceId == userId)
select new
{
ProjectTaskSchedule = projecttaskschedule,
DailyStatus = projecttaskschedule.DailyStatus.Where(t => t.Active),
},
CritiCality = from cr in db.CritiCality.Where(ts => ts.ProjectTaskId == projecttask.ProjectTaskId) select cr,
MMDetails = from mm in db.MMDetails.Where(ts => ts.ProjectTaskId == projecttask.ProjectTaskId) select mm,
MajorMilestone = db.GetMajorMileStone(projecttask.ProjectTaskId).FirstOrDefault(),
}
};
var materialized = query.AsEnumerable();
var result = materialized.Select(t => new ProjectsPayload
{
ProjectId = t.Project.ProjectId,
ProjectTitle = t.Project.ProjectTitle,
Priority = t.Project.Priority,
ProjectDescription = t.Project.ProjectDescription,
ProjectTask = t.Project.ProjectTask.Select(x => new ProjectTaskPayload
{
Duration = x.Duration,
Hours = x.Hours,
IsOngoing = x.IsOngoing,
IsSummaryTask = x.IsSummaryTask,
Priority = x.Priority,
ParentTaskId = x.ParentTaskId,
ProjectId = x.ProjectId,
ProjectTaskId = x.ProjectTaskId,
TaskAcceptanceId = x.TaskAcceptanceId,
TaskStatusId = x.TaskStatusId,
TaskTitle = x.TaskTitle,
TaskTypeId = x.TaskTypeId,
IsMileStone = x.IsMileStone,
IsTimeAwayTask = x.IsTimeAwayTask,
AutoSize = x.AutoSize,
IsArchivedTasksInSummary = x.IsArchivedTasksInSummary,
IsASAP = x.IsASAP,
IsAutoCompleteEnable = x.IsAutoCompleteEnable,
IsSharedDiffSchedules = x.IsSharedDiffSchedules,
LongDescription = x.LongDescription,
OwnerId = x.OwnerId,
ShowInSummaryTask = x.ShowInSummaryTask,
SubTypeID = x.SubTypeID,
MMDetails1 = x.MMDetails1.Select(MD => new MMDetailsPayload { MajorMilestoneId = MD.MajorMilestoneId, ProjectTaskId = MD.ProjectTaskId, MMDetailsId = MD.MMDetailsId, Slack = MD.Slack }),
ProjectTaskSchedule = x.ProjectTaskSchedule.Select(a => new ProjectsTaskSchedulePayload
{
ProjectTaskScheduleId = a.ProjectTaskScheduleId,
StartDate = a.StartDate,
EndDate = a.EndDate,
ProjectTaskId = a.ProjectTaskId,
ResourceId = a.ResourceId,
ArchiveEndDate = a.ArchiveEndDate,
ArchiveStartDate = a.ArchiveStartDate,
IsSharedTask = a.IsSharedTask,
TimeUnitId = a.TimeUnitId,
DailyStatus = a.DailyStatus.Select(Ds => new DailyStatusPayload
{
Active = Ds.Active,
ActualHours = Ds.ActualHours,
DailyStatusId = Ds.DailyStatusId,
Date = Ds.Date,
ProjectTaskScheduleId = Ds.ProjectTaskScheduleId,
IsCloseOutDay = Ds.IsCloseOutDay,
Priority = Ds.Priority
})
}).ToList(),
CritiCality = x.CritiCality.Select(c => new CriticalityPayload { CriticalityId = c.CriticalityId, CriticalityTypeId = c.CriticalityTypeId, ProjectTaskId = c.ProjectTaskId }).ToList(),
}).ToList()
}).FirstOrDefault();
return result;
}
catch (EntityException ex)
{
if (ex.Message == connectionException)
throw new FaultException(dbException);
else
throw new FaultException(ex.Message);
}
}
}
My result is like this, I want all entities(Criticality,MMDetails and MajorMileStone), Not only MajorMileStone
MajorMileStone Result
I separate multiple simple query for testing. Please try to execute below two query and check whether successful or not.
// First query to get project
var query1 = from project in db.Project.Where(t => (t.Active || t.TempActive) && t.ProjectId == projectid)
join UP in db.User_X_Project on project.ProjectId equals UP.ProjectId
where (UP.UserId == userId && UP.Active)
orderby (project.Priority ?? int.MaxValue)
orderby (project.ProjectTitle)
.Select new { project = project }.ToList();
// Second query to get projecttask from query1.project and execute store procedure
var query2 = from projecttask in query1.project.ProjectTask.Where(t => t.Active && (
(includeArchived == true && t.TaskStatusId == (int?)TaskStatus.Archived) ||
(includeArchived == false && t.TaskStatusId != (int?)TaskStatus.Archived)) ||
t.TaskStatusId != (int?)TaskStatus.Planned)
join schedule in query1.project.ProjectTask.SelectMany(p => p.ProjectTaskSchedule) on projecttask.ProjectTaskId equals schedule.ProjectTaskId
join daily in db.ProjectTaskSchedule.SelectMany(p => p.DailyStatus) on schedule.ProjectTaskScheduleId equals daily.ProjectTaskScheduleId
where schedule.Active && daily.Active && projecttask.Active && schedule.ResourceId == userId && (
(EntityFunctions.TruncateTime(daily.Date) >= EntityFunctions.TruncateTime(startDate.Date) &&
EntityFunctions.TruncateTime(daily.Date) <= EntityFunctions.TruncateTime(endDate.Date))
)
orderby schedule.StartDate
.Select new
{
MajorMilestone = db.GetMajorMileStone(projecttask.ProjectTaskId).FirstOrDefault(),
}.ToList();
Let me know it has result or not. In the meantime you can check this "Method cannot be translated into a store expression"
It has link to article about what not to do with linq. Nested Linq like this is best to avoid and better to split up the query. If it affects the execution time, it better to execute raw sql.
var CCEScholasticTests = db.CCEScholasticTests.Where(x => x.CCEvaluationID == CCEValuationID && x.SubjectID == SubjectID && x.ClassID == ClassID && (x.BranchSectionID == BranchSectionID || BranchSectionID == 0) && x.languageTypeSubjectID == languageTypeSubjectID && (x.BranchID == BranchID || x.BranchID == 0) && x.IsOnlyGrade == false).Select(x => x).ToList();
var res = (from a in CCEScholasticTests
join b in db2.CCESubjectSkills on new { key1 = a.CCESubjectSkillID } equals new { key1 = b.CCESubjectSkillID } into join1
from joinRes in join1.DefaultIfEmpty(new CCESubjectSkill())
join c in db2.CCEScholasticSkillsMasters on new { key = joinRes.CCEScholasticSkillMasterID } equals new { key = c.CCEScholasticSkillMasterID } into join2
from joinRes2 in join2.DefaultIfEmpty(new CCEScholasticSkillsMaster())
select new EvaluationBluk
{
BranchSectionID = a.BranchSectionID,
CCEScholasticTestID = a.CCEScholasticTestID,
CCEScholasticTestName = a.CCEScholasticTestName,
//CCESubjectSkillName = joinRes.CCESubjectSkillName,
CCESubjectSkillID = a.CCESubjectSkillID,
CCEvaluationID = a.CCEvaluationID,
MaxMarks = a.MaxMarks,
SubjectID = a.SubjectID,
TestDate = a.TestDate,
MarksEntryLastDate = a.MarksEntryLastDate,
//CCEScholasticSkillMasterID = joinRes.CCEScholasticSkillMasterID,
//CCEScholasticSkillName = joinRes2.CCEScholasticSkillName
}).ToList();
how to write multiple left joins in linq.. the below linq query i am writing based on this sp
CREATE procedure [dbo].[GetClassCCEScholasticTestsOnlyMarksTest]
(
#BranchSectionID int,
#CCEvaluationID int,
#SubjectID int,
#ClassID int ,
#languageTypeSubjectID int ,
#BranchID int
)
as
select c1.BranchSectionID,c1.CCEScholasticTestID,c1.CCEScholasticTestName,s1.CCESubjectSkillName,
c1.CCESubjectSkillID,c1.CCEvaluationID,c1.MaxMarks,c1.SubjectID,convert(varchar,c1.TestDate,101) as TestDate,convert(date,c1.MarksEntryLastDate,101)as MarksEntryLastDate
,isnull(s1.CCEScholasticSkillMasterID,-1) as CCEScholasticSkillMasterID ,cm.CCEScholasticSkillName
from dbo.CCEScholasticTests c1
left join CCESubjectSkills s1 on s1.CCESubjectSkillID=c1.CCESubjectSkillID
left join CCEScholasticSkillsMaster cm on cm.CCEScholasticSkillMasterID=s1.CCEScholasticSkillMasterID
where c1.CCEvaluationID=#CCEvaluationID and c1.SubjectID=#SubjectID
and c1.ClassID=#ClassID and (c1.BranchSectionID=#BranchSectionID or c1.BranchSectionID=0) and c1.languageTypeSubjectID =#languageTypeSubjectID
and (c1.BranchID=#BranchID or c1.BranchID=0)and c1.IsOnlyGrade=0
order by c1.CCEScholasticTestID asc
in sql it throws 3 rows but in linq it throws 1 row only... what wrong in my code
var result=CCEScholasticTests.join(db2.CCESubjectSkills ,o=>o.CCESubjectSkillID, od=>od.CCESubjectSkillID,(o, od)=> new
{
BranchSectionID = o.BranchSectionID,
CCEScholasticTestID = o.CCEScholasticTestID,
CCEScholasticTestName = o.CCEScholasticTestName,
CCESubjectSkillID = o.CCESubjectSkillID,
CCEvaluationID = o.CCEvaluationID,
MaxMarks = o.MaxMarks,
SubjectID = o.SubjectID,
TestDate = o.TestDate,
MarksEntryLastDate = o.MarksEntryLastDate,
CCEScholasticSkillMasterID = od.CCEScholasticSkillMasterID
}).join(db2.CCEScholasticSkillsMasters, s=>s.CCEScholasticSkillMasterID = t.CCEScholasticSkillMasterID, t=>t.CCEScholasticSkillMasterID,(s,t)=> new
{
BranchSectionID = o.BranchSectionID,
CCEScholasticTestID = o.CCEScholasticTestID,
CCEScholasticTestName = o.CCEScholasticTestName,
CCESubjectSkillID = o.CCESubjectSkillID,
CCEvaluationID = o.CCEvaluationID,
MaxMarks = o.MaxMarks,
SubjectID = o.SubjectID,
TestDate = o.TestDate,
MarksEntryLastDate = o.MarksEntryLastDate,
CCESubjectSkillName = t.CCESubjectSkillName,
CCEScholasticSkillMasterID = t.CCEScholasticSkillMasterID,
CCEScholasticSkillName = t.CCEScholasticSkillName
}).tolist();
I dont know the exact relation between the table but, i have assumed and written query. hope it helps u
I am having problems with subqueries in a linq-to-entities IQueryable query.
Can anybody tell me what is the correct way to do a sub query when building up an IQueryable query? Based on my full example below.
I get the following error when ToArray() is called on the query:
An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Data.Entity.IDbSet`1[MyDomain.NewsWorthyPressReleases.NewsWorthyWire] Set[NewsWorthyWire]()' method,
and this method cannot be translated into a store expression.
So for example you can see one of my subqueries here:
BwIncluded = (from abw in Context.Set<NewsWorthyWire>()
where abw.WireId == PressWireIds.BUID
where abw.NewsWorthyCampaignId == nc.Id
select abw).Any(),
I am trying to populate BwIncluded with true or false if any() exists.
And the entire build up of the query is as follows, it is IMPORTANT to understand where the sub-queries are used:
private Func<EntityFramework.IDbContext, IQueryable<NewsWorthyPressRelease>> GetSearchNewsWorthyQuery(NewsWorthySearchFields searchFields)
{
return context =>
{
//domain models
var newsWorthyCampaigns = context.Set<NewsWorthyCampaign>();
var wires = context.Set<NewsWorthyWire>();
var campaigns = context.Set<Campaign>();
//predicates
var newsWorthyCampaignPredicate = PredicateBuilder.True<NewsWorthyCampaign>();
var wirePredicate = PredicateBuilder.True<NewsWorthyWire>();
var campaignPredicate = PredicateBuilder.True<Campaign>();
// build up the predicate queries
//Status was input
if (searchFields.StatusId.HasValue && searchFields.StatusId.Value > 0)
{
newsWorthyCampaignPredicate = newsWorthyCampaignPredicate.And(x => x.Id == searchFields.StatusId);
}
//Id was input
if (searchFields.Id.HasValue && searchFields.Id.Value > 0)
{
wirePredicate = wirePredicate.And(x => x.Id == searchFields.Id);
}
//Title was input
if (!string.IsNullOrEmpty(searchFields.Title))
{
wirePredicate = wirePredicate.And(x => x.Title.Contains(searchFields.Title));
}
//Wire was input
if (searchFields.PressWireId.HasValue && searchFields.PressWireId.Value > 0)
{
wirePredicate = wirePredicate.And(x => x.Id == searchFields.PressWireId);
}
//Created By was chosen
if (searchFields.CreatedById.HasValue && searchFields.CreatedById.Value > 0)
{
campaignPredicate = campaignPredicate.And(x => x.IdentityId == searchFields.CreatedById);
}
//Create Date From was chosen
if (searchFields.DateCreatedFrom.HasValue)
{
campaignPredicate = campaignPredicate.And(y => y.CreationDate >= searchFields.DateCreatedFrom);
}
//Create Date To was chosen
if (searchFields.DateCreatedTo.HasValue)
{
campaignPredicate = campaignPredicate.And(y => y.CreationDate <= searchFields.DateCreatedTo);
}
//the query
var nwprQuery = (from nc in newsWorthyCampaigns.Where(newsWorthyCampaignPredicate)
join w in wires.Where(wirePredicate)
on nc.Id equals w.NewsWorthyCampaignId
join c in campaigns.Where(campaignPredicate)
on nc.CampaignId equals c.Id
select new NewsWorthyPressRelease
{
Id = nc.Id,
Title = w.Title,
//BwIncluded = false,
//GnIncluded = false,
//PrIncluded = false,
BwIncluded = (from abw in Context.Set<NewsWorthyWire>()
where abw.WireId == PressWireIds.BUID
where abw.NewsWorthyCampaignId == nc.Id
select abw).Any(),
GnIncluded = (from agw in Context.Set<NewsWorthyWire>()
where agw.WireId == PressWireIds.GLID
where agw.NewsWorthyCampaignId == nc.Id
select agw).Any(),
PrIncluded = (from anw in Context.Set<NewsWorthyWire>()
where anw.WireId == PressWireIds.PRID
where anw.NewsWorthyCampaignId == nc.Id
select anw).Any(),
CreatedBy = c.CreatedBy.FirstName + " " + c.CreatedBy.Surname,
CreateDate = c.CreationDate,
Status = nc.NewsWorthyStatus.Name,
}).AsNoTracking();
return nwprQuery;
};
}
Can anyone help with this?
Thanks
In my method I have multiple statements that are filtering data and returning and object. Because I want to serve the view with an view model I instantiate a list and then pass it into view...
Simplified example.
List<viewModel> returnedViewModel = new List<viewModel>();
foreach (var item in filteredData)
{
returnedViewModel.Add( // this line is throwing error
new viewModel
{
data = item,
});
}
The issue is that I'm getting "Object reference not set to an instance of an object." for returnedViewModel.Add for one particular filteredData object while other are not causing that issue.
I'm after a possible source of that problem not the solution.
I'm using EF and have a MARS statement in my connectionString. Can that be an issue?
Whole statment:
public ActionResult RenderPartialSearchableEventStacks(string viewType,
string orderColumn,
string sortOrder,
int? stackNumber,
string adminName,
string clientName,
string stackType,
string stackStatus,
int? adminId = null)
{
IEnumerable<blsEventStack> eventStacks = unitOfWork.EventStackRepository.Filter(n => (stackNumber == null) || n.EventStackId == stackNumber,
n => (String.IsNullOrEmpty(adminName)) || n.ManagingAdminName.Contains(adminName),
n => (String.IsNullOrEmpty(clientName)) || n.RelatedClientName.Contains(clientName),
n => (String.IsNullOrEmpty(stackType)) || n.EventStackType.Contains(stackType),
n => (String.IsNullOrEmpty(stackStatus)) || n.EventStackLastEventStatus.Contains(stackStatus));
IEnumerable<blsEventStack> viewTypeRelatedEventStacks = eventStacks;
if (viewType == "allEventStacks")
{
viewTypeRelatedEventStacks = unitOfWork.EventStackRepository.GetAll();
}
if (viewType == "assignedEventStacks")
{
// Needed to filter out results with empty (unassigned) admin name
viewTypeRelatedEventStacks = from x in eventStacks
where x.ManagingAdminName != null
select x;
}
if (viewType == "singleAdminAssignedEventStacks")
{
string singleAdminName;
if (adminId != null)
{
// Gets admin name using adminId
singleAdminName = unitOfWork.AdminRepository.GetById(adminId).AdminName;
}
else
{
MembershipUser admin = Membership.GetUser();
blsAdmin loggedInAdmin = (from x in unitOfWork.AdminRepository.GetAll()
where x.AdminEmail == admin.Email
select x).FirstOrDefault();
singleAdminName = loggedInAdmin.AdminName;
ViewBag.adminView = true;
}
// Gets all eventStacks that belong to a give adminName
viewTypeRelatedEventStacks = from x in eventStacks
where x.ManagingAdminName == singleAdminName
select x;
ViewBag.adminId = adminId;
}
IEnumerable<blsEventStack> returnedEventStacks = viewTypeRelatedEventStacks;
if (orderColumn == "stack")
{
if (sortOrder == "descendingStack")
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackId descending
select x;
sortOrder = null;
}
else
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
select x;
sortOrder = "descendingStack";
}
}
if (orderColumn == "managingAdmin")
{
if (sortOrder == "descendingManagingAdmin")
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.ManagingAdminName descending
select x;
sortOrder = null;
}
else
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.ManagingAdminName
select x;
sortOrder = "descendingManagingAdmin";
}
}
if (orderColumn == "relatedClient")
{
if (sortOrder == "descendingRelatedClient")
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.RelatedClientName descending
select x;
sortOrder = null;
}
else
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.RelatedClientName
select x;
sortOrder = "descendingRelatedClient";
}
}
if (orderColumn == "stackType")
{
if (sortOrder == "descendingStackType")
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackType descending
select x;
sortOrder = null;
}
else
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackType
select x;
sortOrder = "descendingStackType";
}
}
if (orderColumn == "latestEventTime")
{
if (sortOrder == "descendingLatestEventTime")
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackLastEventTime descending
select x;
sortOrder = null;
}
else
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackLastEventTime
select x;
sortOrder = "descendingLatestEventTime";
}
}
if (orderColumn == "latestEventStatus")
{
if (sortOrder == "descendingLatestEventStatus")
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackLastEventStatus descending
select x;
sortOrder = null;
}
else
{
returnedEventStacks = from x in viewTypeRelatedEventStacks
orderby x.EventStackLastEventStatus
select x;
sortOrder = "descendingLatestEventStatus";
}
}
List<ViewModelAllEventStacks> returnedViewModel = new List<ViewModelAllEventStacks>();
foreach (var item in returnedEventStacks)
{
returnedViewModel.Add(
new ViewModelAllEventStacks
{
EventStack = item,
AdminId = item.AdminEventLogs.FirstOrDefault().AdminId,
ClientId = item.ClientEventLogs.FirstOrDefault().ClientId
});
}
ViewBag.stackNumber = stackNumber;
ViewBag.adminName = adminName;
ViewBag.clientName = clientName;
ViewBag.stackType = stackType;
ViewBag.stackStatus = stackStatus;
// ViewBag passing state of existing order
ViewBag.sortOrder = sortOrder;
// ViewBag passing view data (ex. assignedEventStacks, allEventStacks, etc.)
ViewBag.viewType = viewType;
return PartialView("BLS_AllEventStacks", returnedViewModel);
}
There are 4 possible reasons:
Your code in debug isn't what's actually running and is stale.
There is a null exception in the viewModel constructor.
There is a null exception happening in the data property.
As noted in the comments, there is some code you filtered out that was actually setting the list to null.
Based on edited question
returnedViewModel.Add(
new ViewModelAllEventStacks
{
EventStack = item,
AdminId = item.AdminEventLogs.FirstOrDefault().AdminId,
ClientId = item.ClientEventLogs.FirstOrDefault().ClientId
});
if there are no AdminEventLogs or ClientEventLogs this will throw the null exception error. Also possible but unlikely, item is null.
I believe these two lines are the problem. When you use item.AdminEventLogs.FirstOrDefault(), it will be null if item.AdminEventLogs doesn't have any elements, so accessing .AdminId will raise an error. The same thing also applies to item.ClientEventLogs.FirstOrDefault()
AdminId = item.AdminEventLogs.FirstOrDefault().AdminId,
ClientId = item.ClientEventLogs.FirstOrDefault().ClientId
You can use .Any() to check whether item.AdminEventLogs and item.ClientEventLogs have any elements. If so, use the AdminId and ClientId of the first element, otherwise set AdminId and ClientId to 0 (assuming AdminId and ClientId are integers)
AdminId = item.AdminEventLogs.Any() ? item.AdminEventLogs.First().AdminId : 0,
ClientId = item.ClientEventLogs.Any() ? item.ClientEventLogs.First().ClientId : 0