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

Entity framework - selecting from child lists without getting top level object

在我的模型中,"User" 有 "Projects"。

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 没有对象关系,但这会破坏其他事情,因为其他事情需要这种关系。

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

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;}
}