EF Code First迁移创建额外的外键 [英] EF Code First Migrations creating extra foreign key

查看:114
本文介绍了EF Code First迁移创建额外的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个个人资料表以与Asp.Net Identity表集成: AspNetUsers 。我在EF 6.0中使用了代码优先迁移。

I'm trying to create a Profile table to integrate with the Asp.Net Identity table: AspNetUsers. I'm using Code First Migrations with EF 6.0.

这是我的用户类:

public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {

        }


        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public UserStatus Status { get; set; }
        public virtual Profile Profile { get; set; }
    }

这是我的个人资料类别:

Here is my Profile class:

public class Profile
    {
        public int ID { get; set; }
        public string ApplicationUserID { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

我在DataContext中具有配置:

I have the configuration in my DataContext:

modelBuilder.Entity<Profile>()
                .HasRequired<ApplicationUser>(m => m.ApplicationUser);

奇怪的是,当我运行迁移时,当我全部迁移时,它将在数据库中创建ApplicationUserID和ApplicationUser_Id想要创建ApplicationUserID并将其用作外键列。如果我添加属性AppliationUser_Id,则会添加ApplicationUser_Id1。有人知道如何解决这个问题吗?

The weird thing is that when I run the migration it creates ApplicationUserID and ApplicationUser_Id in the database when all I want is to create ApplicationUserID and use that as the foreign key column. If I add the property AppliationUser_Id it'll add ApplicationUser_Id1. Anyone know how to fix this?

我要确保外键在配置文件表上,即Profile拥有ApplicationUserID列,反之亦然我不希望AspNetUsers表具有profile_ID列。

PS我使用的是Fluent API,而不是数据注释。

P.S. I'm using Fluent API, not data annotations.

推荐答案

如果要配置一对一关系,则实体框架需要

If you want to configure an one to one relationship, Entity Framework requires that the primary key of the dependent must be used as the foreign key.

public class Profile
{
    public string ApplicationUserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

现在,由于该限制,关于FK公约,因为存在

Now, about the FK convention, due to that restriction, since there is no choice, Code First will just infer the FK for you.

另一件事是,使用Fluent Api配置一对一关系的正确方法是:

Another thing is, the proper way to configure one-to-one relationship using Fluent Api is:

modelBuilder.Entity<Profile>()
            .HasRequired<ApplicationUser>(m => m.ApplicationUser)
            .WithOptional(a=>a.Profile);

这篇关于EF Code First迁移创建额外的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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