11

I am trying to create a one to one relationship using C# in Entity Framework 6 using ASP.NET MVC 5 with built-in user authentication.

I am able to make tables and connections with the defaults that Entity Framework creates. But when I try to use fluent API.... more specifically when I use on model creating even empty my database migration using the package manager console will fails. How can I map my one to one relationship?

My error:

//error
//my.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined.   //Define the key for this EntityType.
//my.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. //Define the key for this EntityType.
//IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type    //'IdentityUserLogin' that has no keys defined.
//IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type //'IdentityUserRole' that has no keys defined.

My Code:

namespace my.Models
{

    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

        public DbSet<EngineeringProject> EngineeringProjects { get; set; }

        public DbSet<EngineeringProject> EngineeringDesigns { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new EngineeringDesignMap());
            modelBuilder.Configurations.Add(new EngineeringProjectMap());
        }

    }
}

namespace my.Models.Mapping
{
    public class EngineeringProjectMap : EntityTypeConfiguration<EngineeringProject>
    {
        public EngineeringProjectMap()
        {
            this.HasRequired(t => t.EngineeringPd)
                .WithOptional(t => t.EngineeringProject);
            this.HasRequired(t => t.EngineeringProjectCategory)
                .WithMany(t => t.EngineeringProjects)
                .HasForeignKey(d => d.CategoryId);
        }
    }
}
4

2 回答 2

19

发生错误是因为派生的标识表在派生的上下文中具有映射。这需要在新的 OnModelCreating 覆盖函数中调用。为此,只需将 base.OnModelCreating(modelBuilder) 添加到您的方法中,如下所示。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    base.OnModelCreating(modelBuilder); // <-- This is the important part!
    modelBuilder.Configurations.Add(new EngineeringDesignMap());
    modelBuilder.Configurations.Add(new EngineeringProjectMap());
}
于 2013-10-21T02:24:41.160 回答
7

看起来您缺少对base.OnModelCreatingDbContext 中的调用。

于 2013-10-19T00:27:01.063 回答