How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

后端 未结 3 490
面向向阳花
面向向阳花 2020-12-02 14:22

I\'m new to using LINQ to Entities (or Entity Framework whatever they\'re calling it) and I\'m writing a lot of code like this:

var item = (from InventoryIte         


        
相关标签:
3条回答
  • 2020-12-02 14:48

    You want to use the .Include(string) method references in this "Shaping query results" article.

    var item = from InventoryItem item in
                  db.Inventory.Include("ItemTypeReference").Include("OrderLineItems")
               where item.ID == id
               select item;
    

    There is probably a "sql" style syntax for the Includes as well.

    Also see this article about moving from LINQ-to-SQL to LINQ-to-Entities.

    For others looking for a solution to this problem for Linq to SQL you want to do the following (Substitute DataContext and other types for whatever you have):

    using (DataContext db = new DataContext())
    {
        DataLoadOptions options = new DataLoadOptions();
        options.LoadWith<InventoryItem>(ii => ii.ItemTypeReference);
        options.LoadWith<InventoryItem>(ii => ii.OrderLineItems);
        db.LoadOptions = options;
    
        var item = from InventoryItem item in db.Inventory
                   where item.ID == id
                   select item;
    }
    

    This will load the properties specified in LoadWith whenever the parent item (InventoryItem) is loaded, for that particular context.

    In response to some further questions from James and Jesper, check out this question

    0 讨论(0)
  • 2020-12-02 14:49

    In addition to Robert's answer, you might like to check out this question for options for an extension method that that allows you to .Include() using an expression instead of a string, so you get compile time checking:

    Entity Framework .Include() with compile time checking?

    0 讨论(0)
  • 2020-12-02 15:11

    AFAIK, For silverlight(domain services) adding [Include] attribute to right place(over navigation property in metadata) is enough https://stackoverflow.com/a/5332188/413032

    0 讨论(0)
提交回复
热议问题