如何在 MVC 5 实体框架 6 中使用流畅 ASP.NET API 映射表
本文关键字:ASP NET 映射 API MVC 实体 框架 | 更新日期: 2023-09-27 18:35:54
我正在尝试使用具有内置用户身份验证 ASP.NET MVC 5 在实体框架 6 中使用 C# 创建一对一关系。
我能够使用实体框架创建的默认值建立表和连接。但是当我尝试使用流畅的 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);
}
}
}
发生这些错误的原因是派生标识表在派生上下文中具有映射。这需要在新的 OnModelCreate 覆盖函数中调用。为此,只需添加底座即可。OnModelCreateating(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());
}
看起来
您在 DbContext 中缺少对base.OnModelCreating
的调用。