EF Code First Migrations creating extra foreign key

北战南征 提交于 2019-12-10 19:50:29

问题


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.

Here is my User class:

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

I have the configuration in my DataContext:

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

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?

I want to make sure that the Foreign Key is on the profile table i.e. Profile has the column ApplicationUserID and not vice versa i.e. I don't want the AspNetUsers table to have a profile_ID column.

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


回答1:


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

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

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


来源:https://stackoverflow.com/questions/34661544/ef-code-first-migrations-creating-extra-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!