c# - EF Code First Migrations 创建额外的外键

标签 c# .net entity-framework ef-code-first entity-framework-migrations

我正在尝试创建一个 Profile 表以与 Asp.Net Identity 表集成:AspNetUsers。我在 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; }
    }

这是我的个人资料类:

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

我的 DataContext 中有配置:

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

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

我想确保外键位于配置文件表上,即配置文件具有 ApplicationUserID 列,反之亦然,即我不希望 AspNetUsers 表具有 profile_ID 列。

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

最佳答案

如果要配置一对一关系,Entity Framework要求必须使用依赖的主键作为外键。

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

现在,关于 FK 约定,由于该限制,由于别无选择,Code First 只会为您推断 FK。

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

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

关于c# - EF Code First Migrations 创建额外的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34661544/

相关文章:

c# - Entity Framework 如何查看 SaveChanges 方法的 SQL 语句

c# - 无法将类型 system.data.entitystate 隐式转换为 system.data.entity.entitystate(您是否缺少强制转换?)

c# - 代码优先自引用外键(多个)

c# - 有没有办法将这两个 LINQ 语句合并为一个

c# - 在高频交易中尝试并行处理订单是否有意义?

c# - 如何将 datetimepicker 值设置为仅日期 (.NET)

.net - ASP.NET 将 CORS header 添加到 ashx 文件处理程序

c# - 在 C# 中显示完整的 SSH shell 输出,包括登录消息和提示

c# - 在特定行读取文本文件

c# - Domain Admins 组的 IsUserInRole 问题(不是配置问题)