我有下面定义的代码第一个模型。
Project和TeamMember之间有两种关系:
一对多 - 项目总是有一个TeamMember作为经理。
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
}
此模型生成如下所示的Project表定义。
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]));
我需要使用Manager的外键属性扩展Project,但无法做到这一点。
public Guid ManagerId { get; set; } // 2
[InverseProperty("ManagedProjects")]
public virtual TeamMember Manager { get; set; } // 2
上面的代码不起作用,因为它只在Project表中生成一个ManagerId字段。我尝试过不同的ForeignKey og InverseProperty组合而没有任何运气。
有什么建议吗?
答案 0 :(得分:0)
下一个代码应为多对多创建连接表,'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
}
我认为没有连接表就不可能有多对多的关系。