我的项目上的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; }
}
答案 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)