实体框架一对一或一个外键关联 [英] Entity Framework one-to-zero-or-one foreign key association

查看:126
本文介绍了实体框架一对一或一个外键关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将现有应用程序的后端更改为首先使用实体​​框架代码。我使用Visual Studio 2015中的内置工具根据我现有的数据库生成POCO类。这大部分工作完美,除了两个类别之外,具有一对一或一个关系。这些是我的(简化)课程:

I am in the process of changing the back-end of an existing application to use Entity Framework Code First. I've used the built-in tool in Visual Studio 2015 to generate POCO classes based on my existing database. This worked perfectly for the most part, except for two classes, with a one-to-zero-or-one relationship. These are my (simplified) classes:

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 ] 而不是 [登录]。[TeamMember_Id] 。我已经尝试使用 ForeignKey 属性来装饰我的导航属性,但这没有起作用。有没有办法让它在 [Logins] [[TeamMember_Id] 上创建一个外键?

For some reason EF creates a foreign key on [Logins].[Id] instead of [Logins].[TeamMember_Id]. I've already tried decorating my navigation property with a ForeignKey attribute, but this did not work. Is there a way to get it to create a foreign key on [Logins].[TeamMember_Id] instead?

推荐答案

我最终创建了一对多关系,一个 [NotMapped] 属性用于登录。

I ended up creating one-to-many relationship, with a [NotMapped] property for Login.

我的课程:

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");
    }
}

这篇关于实体框架一对一或一个外键关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆