entity-framework - 禁用延迟加载时,如何仅将导航属性的特定属性包含到实体框架的查询中?
问题描述
我的项目禁用了延迟加载。我想获得具有其类别导航属性的 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; }
}
解决方案
如果您只需要几个特定字段,则需要明确选择它们。像这样的东西会起作用:
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 对象,该对象缺少调用者可能不期望的大多数字段的值。取决于你到底在做什么。
推荐阅读
- google-apps-script - 我的 Slack Bot 使用 Google API 为使用服务帐户的用户生成包含数据的 Google 表格,如何向该表格添加脚本
- cypress - 在 react 项目中使用 cypress 时如何获取 url 值并与输入值进行比较?
- javascript - Apache Echarts - 创建拖放效果
- scala - Scala - 使用随机数元组创建 seq
- r - 无法在 R 中模拟具有已知相关性和约束的比例
- arrays - 在不超载内存的情况下对 UIView 进行多张截图
- ios - WKWebview 服务工作者
- python-3.x - 从python读取二维数组文本文件时出现问题
- javascript - 如何在 Google App Scipt 中插入此表情符号?
- javascript - 基于枚举的 AJV if-then-else 条件类型