gur*_*aym 4 entity-framework lazy-loading entity-framework-core
我的项目禁用了 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; }
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要几个特定字段,则需要明确选择它们。像这样的事情会起作用:
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
}
}
Run Code Online (Sandbox Code Playgroud)
最好有一个仅包含两个字段的产品和类别模型类。现在,您的方法将返回一个 Category 对象,该对象缺少调用者可能不期望的大多数字段的值。取决于你到底在做什么。
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |