禁用延迟加载时,如何仅通过实体框架将导航属性的特定属性包含到查询中?

时间:2019-02-03 13:43:35

标签: entity-framework entity-framework-core lazy-loading

我的项目上的LazyLoading已禁用。我想获得ID = 1的具有类别导航属性的产品。但是我只需要类别的Id和Name属性。这就是为什么我希望类别导航属性仅具有这两个字段。是否可以创建这样的查询?

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } 
    public dobule Price{ get; set; }
    public string Description { get; set; }
    public bool IsDeleted { get; set; }       
    public DateTime CreatedDate { get; set; }   
    public DateTime ModifiedDate { get; set; }      

    public int CategoryId{ get; set; }
    public Category Category{ get; set; }  
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; } 
    public dobule Description{ get; set; }
    public Category IsDeleted { get; set; }       
    public DateTime CreatedDate { get; set; }   
    public DateTime ModifiedDate { get; set; } 
}

2 个答案:

答案 0 :(得分:1)

如果只需要一些特定字段,则需要明确选择它们。这样的事情会起作用:

dbContext.Products
    .Select(p => new Product
    {
        Id = p.Id,
        Name = p.Name,
        // etc... The fields you need from product go here
        Category = new Category
        {
            Id = p.Category.Id,
            Name = p.Category.Name
        }
    }

最好让Product和Category模型类仅包含两个字段。现在,您的方法将返回一个Category对象,该对象缺少调用者可能不希望的大多数字段的值。取决于您到底在做什么。

答案 1 :(得分:0)

取决于在调用数据库之前是否知道想要什么。

  1. 如果您知道什么,则可以使用一些“包含”逻辑或@Sangman的awnser或检查文档here

  2. 如果内存中已经有该实体,则决定加载其他导航属性。

context.Entry(yourEntity).Reference(a => a.Category).Load();

更多示例here