Search code examples
c#.netentity-frameworkentity-framework-4self-tracking-entities

With entity framework's self tracking entities, can I perform an explicit load?


I wish to return a graph for a "Business" entity. The Buiness entity has a collection of "Contacts".

So I basically want this:

ctx.Business.Include("Contacts").Where(b => b.BusinessID == id).Single();

The problem is I don't want ALL the contacts for the business. Just those that have a ContactTypeID = x. How can I accomplish this? I figured I may need to break the query into 2 steps. 1 to get the business and a 2nd to grab the contacts and then attach them to the business somehow.

But I'm using using the STE t4 template and I can't figure out how to do it using that.

I'd greatly appreciate any help.


Solution

  • I think I found how to do it:

    var biz = ctx.Business.Where(b => b.BusinessID == id).Single(); 
    var contacts = ctx.Contacts.Where(c => c.BusinessID==id && c.ContactTypeID==6);
    foreach (var contact in contacts)
    {
       biz.Contacts.Add(contact);
    }
    

    I was worried by adding the contacts this way they would be treated as "new" items but change tracking is off so they are treated as unchanged. I think change tracking only turns on once they are deserialized.