在我的模型中,“用户”有“项目”。
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对象引用吗?
答案 0 :(得分:3)
如何通过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;}
}