select specific columns when using include statement with entity framework

后端 未结 1 493
逝去的感伤
逝去的感伤 2020-12-15 18:26

When I need a hierarchal (parent-child) relationship, I typically use the Include statement in my EF query.

Example:

DbContext.Customers.Include(\"Pr         


        
相关标签:
1条回答
  • 2020-12-15 18:51

    Check this link for more details. In short, the trick is to use .Select() and anonymous type to restrict the columns you want. In the example below first Select() is actually doing this:

    var results = context.Products
            .Include("ProductSubcategory")
            .Where(p => p.Name.Contains(searchTerm)
                        && p.DiscontinuedDate == null)
            .Select(p => new
                            {
                                p.ProductID,
                                ProductSubcategoryName = p.ProductSubcategory.Name,
                                p.Name,
                                p.StandardCost
                            })
            .AsEnumerable()
            .Select(p => new AutoCompleteData
                                {
                                    Id = p.ProductID,
                                    Text = BuildAutoCompleteText(p.Name,
                                        p.ProductSubcategoryName, p.StandardCost)
                                })
            .ToArray();
    
    0 讨论(0)
提交回复
热议问题