gpt4 book ai didi

entity-framework - 禁用延迟加载时,如何仅将导航属性的特定属性包含到 Entity Framework 的查询中?

转载 作者:行者123 更新时间:2023-12-04 14:21:19 25 4
gpt4 key购买 nike

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

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

关于entity-framework - 禁用延迟加载时,如何仅将导航属性的特定属性包含到 Entity Framework 的查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com