【问题标题】:How can I map tables using fluent API in ASP.NET MVC 5, Entity Framework 6?如何在 ASP.NET MVC 5、Entity Framework 6 中使用流利的 API 映射表?
【发布时间】:2013-10-27 17:22:32
【问题描述】:

我正在尝试使用带有内置用户身份验证的 ASP.NET MVC 5 在 Entity Framework 6 中使用 C# 创建一对一的关系。

我能够使用 Entity Framework 创建的默认值创建表和连接。但是当我尝试使用流利的 API 时......更具体地说,当我使用模型创建时,即使使用包管理器控制台为空我的数据库迁移也会失败。如何映射我的一对一关系?

我的错误:

//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.

我的代码:

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

【问题讨论】:

  • 没有定义键 您有什么不清楚的地方? IdentityUser 长什么样子?

标签: c# entity-framework entity-framework-6 asp.net-mvc-5 asp.net-identity


【解决方案1】:

发生错误是因为派生的身份表在派生上下文中有映射。这需要在新的 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());
}

【讨论】:

    【解决方案2】:

    您的 DbContext 中似乎缺少对 base.OnModelCreating 的调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-28
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多