gpt4 book ai didi

c# - Entity Framework - 从子列表中选择而不获取顶级对象

转载 作者:行者123 更新时间:2023-11-30 21:46:09 24 4
gpt4 key购买 nike

在我的模型中,“用户”有“项目”。

public class User
{
public int Id { get; set; }
public virtual List<Project> Projects { get; set; }
}

(除其他事项外)。

在代码中,我想获取项目列表:

var p = _context.User(x => x.Id == someUserId).Projects;

这也在拉用户对象,但我不希望它这样做(这是浪费精力)。

我可以将我的项目模型更改为与 User 没有对象关系,但这会破坏其他事情,因为其他事情需要这种关系。

实现此目标的最佳方法是什么?在 Project 类上,我可以同时拥有 UserId 和 User 对象引用吗?

最佳答案

如何通过 Projects 而不是 Users 开始查询?我认为您可能在 Project 实体中有一个 Fk 属性引用相关的 User:

var projects=_context.Projects.Where(p=>p.UserId==someUserId);

因此,您的 Project 实体应该具有这两个属性

public class Project
{
//other properties


//FYI, EF by a name convention will use this property as FK,
//but is a good practice specify explicitly which is the FK in a relationship
[ForeignKey("User")]
public int UserId{get;set;}

public virtual User User{get;set;}
}

关于c# - Entity Framework - 从子列表中选择而不获取顶级对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39470657/

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