EF Code First -如何在使用InverseProperty时添加外键属性
本文关键字:InverseProperty 添加 属性 First Code EF | 更新日期: 2023-09-27 18:13:28
下面定义了代码第一模型。
Project和TeamMember之间有两种关系:
- 多对多-团队成员可以在多个项目中工作。项目可以有多个TeamMembers。
-
一对多-项目总是有一个TeamMember作为Manager。
public class Project { public Guid ProjectId { get; set; } [InverseProperty("ManagedProjects"), Required] public virtual TeamMember Manager { get; set; } // 2 public virtual List<TeamMember> TeamMembers { get; set; } // 1 } public class TeamMember { public Guid TeamMemberId { get; set; } public virtual List<Project> Projects { get; set; } // 1 [InverseProperty("Manager")] public virtual List<Project> ManagedProjects { get; set; } // 2 }
该模型生成如下所示的项目表定义。
CREATE TABLE [dbo].[Project] (
[ProjectId] UNIQUEIDENTIFIER NOT NULL,
[Manager_TeamMemberId] UNIQUEIDENTIFIER NOT NULL,
CONSTRAINT [PK_dbo.Project] PRIMARY KEY CLUSTERED ([ProjectId] ASC),
CONSTRAINT [FK_dbo.Project_dbo.TeamMember_Manager_TeamMemberId] FOREIGN KEY
([Manager_TeamMemberId]) REFERENCES [dbo].[TeamMember] ([TeamMemberId]));
我需要用管理器的外键属性扩展项目,但无法做到这一点。
public Guid ManagerId { get; set; } // 2
[InverseProperty("ManagedProjects")]
public virtual TeamMember Manager { get; set; } // 2
上面的代码不起作用,因为它只是在Project表中生成一个ManagerId字段。我已经尝试了不同的组合ForeignKey和InverseProperty没有任何运气。
有什么建议吗?
接下来的代码应该创建多对多连接表,并且'Project'表将在该表上具有外键。
public class Project
{
public Guid ProjectId { get; set; }
public virtual TeamMember Manager { get; set; } // 2
[InverseProperty("Projects")]
public virtual List<TeamMember> TeamMembers { get; set; } // 1
}
public class TeamMember
{
public Guid TeamMemberId { get; set; }
[InverseProperty("TeamMembers")]
public virtual List<Project> Projects { get; set; } // 1
[InverseProperty("Manager")]
public virtual List<Project> ManagedProjects { get; set; } // 2
}