实体框架一对多或一个外键关联

时间:2016-08-10 08:30:32

标签: c# entity-framework ef-code-first foreign-keys entity-framework-6

我正在更改现有应用程序的后端以使用Entity Framework Code First。我已经使用Visual Studio 2015中的内置工具根据我现有的数据库生成POCO类。这在大多数情况下都是完美的,除了两个类,一对一或零关系。这些是我的(简化)类:

public class Login
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int TeamMemberId { get; set; }
    public virtual TeamMember TeamMember { get; set; }
}

public class TeamMember
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual Login Login { get; set; }
}

使用以下配置:

public class LoginTypeConfiguration : EntityTypeConfiguration<Login>
{
    public LoginTypeConfiguration()
    {
        this.HasRequired(e => e.TeamMember)
            .WithOptional(e => e.Login);

        this.Property(e => e.TeamMemberId)
            .HasColumnName("TeamMember_Id");
    }
}

这导致以下迁移:

CreateTable(
    "dbo.Logins",
    c => new
        {
            Id = c.Int(nullable: false, identity: true),
            TeamMember_Id = c.Int(nullable: false),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.TeamMembers", t => t.Id)
    .Index(t => t.Id);

由于某些原因,EF会在[Logins].[Id]而不是[Logins].[TeamMember_Id]上创建外键。我已经尝试使用ForeignKey属性装饰我的导航属性,但这不起作用。有没有办法让它在[Logins].[TeamMember_Id]上创建外键?

2 个答案:

答案 0 :(得分:0)

为此,您可以像这样首先编写代码。实体框架将自动为您生成外键TeamMemberId。有关详细信息:Entity Framework Tutorial - Code First Conventions

public class Login
{
   public int Id { get; set; } //foreign key declaration
   public int TeamMemberId { get; set; }
   public  TeamMember TeamMember { get; set; }
}

public class TeamMember
{
   public int TeamMemberId { get; set; }
   public Ilist<Login> Login { get; set; }
}

答案 1 :(得分:0)

我最终创建了一对多关系,并为登录设置了[NotMapped]属性。

我的课程:

public class Login
{
    public int TeamMemberId { get; set; }
    public virtual TeamMember TeamMember { get; set; }
}

public class TeamMember
{
    [NotMapped]
    public virtual Login Login
    {
        get { return Logins.FirstOrDefault(); }
    }

    public virtual ICollection<Login> Logins { get; set; }
}

使用以下配置:

public class LoginTypeConfiguration : EntityTypeConfiguration<Login>
{
    public LoginTypeConfiguration()
    {
        this.Property(e => e.TeamMemberId)
            .HasColumnName("TeamMember_Id");
    }
}