Sameer Kamran
Sameer Kamran

Reputation: 247

c# Lambda Query fetching one of the property weirdly null

    [HttpGet]
    public ActionResult SecondMission(string Id)
    {
        CATSDDEntities db = new CATSDDEntities();
        db.Configuration.ProxyCreationEnabled = false;
        var setAlet= db.Setalets.Where(x => x.Aletler.Barkod == Id && x.Bolum == 1).Include(x => x.Aletler.AletAD).Include(x => x.Setler).FirstOrDefault();
        if (setAlet == null)
        {
            return Json("Error, Alet Not Found!", JsonRequestBehavior.AllowGet);
        }
        else
        {
            setAlet.Bolum = 2;
            db.SaveChanges();
            var MissionTwoSets = db.Setalets.Where(x => x.Bolum == 2 && x.SetId==setAlet.SetId).Include(x => x.Aletler.AletAD).Include(x => x.Setler).GroupBy(x => x.SetId).ToList();
            return PartialView("~/Views/Shared/_SecondMissionSetPartial.cshtml", MissionTwoSets);
        }
    }

I am calling this method by ajax

When i call this method first time.. Aletler property of MissionTwoSets have data.. but when i call this method second time and fetch multiple data.. one of the item get null in Aletler(LOOK) .. its quite weird.. im using the same code somewhere else using same data and working fine..

Upvotes: 3

Views: 114

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205759

Includes are ignored (have no effect) in GroupBy queries, so normally the navigation properties would be null.

However what you see is a result of the context tracking. Since you first load a single entity, it's eager loaded properties are not null. Then when you execute the GroupBy which result includes the already loaded (tracked) entity, then EF reuses that instance and hence it would still have navigation properties populated. All other entities would have null navigation properties due to the aforementioned "ignored includes".

Since the GroupBy query like this makes no sense to be executed server side (has no SQL equivalent), the solution is to execute the GroupBy part client side (by inserting the typical AsEnumerable() before it), thus keeping the includes in effect:

var MissionTwoSets = db.Setalets
    .Where(x => x.Bolum == 2 && x.SetId==setAlet.SetId)
    .Include(x => x.Aletler.AletAD)
    .Include(x => x.Setler)
    .AsEnumerable() // <-- switch to LINQ to Objects
    .GroupBy(x => x.SetId)
    .ToList();

Upvotes: 4

Related Questions