首页 > 解决方案 > 禁用延迟加载时,如何仅将导航属性的特定属性包含到实体框架的查询中?

问题描述

我的项目禁用了延迟加载。我想获得具有其类别导航属性的 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; } 
}

标签: entity-frameworkentity-framework-corelazy-loading

解决方案


如果您只需要几个特定字段,则需要明确选择它们。像这样的东西会起作用:

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 对象,该对象缺少调用者可能不期望的大多数字段的值。取决于你到底在做什么。


推荐阅读