EF Code First - 使用InverseProperty时如何添加外键属性?

时间:2014-07-18 19:26:37

标签: c# entity-framework code-first

我有下面定义的代码第一个模型。

Project和TeamMember之间有两种关系:

  1. 多对多 - TeamMember可以处理许多项目。项目可以有很多TeamMembers。
  2. 一对多 - 项目总是有一个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
    }
    
  3. 此模型生成如下所示的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组合而没有任何运气。

    有什么建议吗?

1 个答案:

答案 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
}

我认为没有连接表就不可能有多对多的关系。