gpt4 book ai didi

c# - 如何在 ASP.NET MVC 5、Entity Framework 6 中使用流畅的 API 映射表?

转载 作者:可可西里 更新时间:2023-11-01 08:34:39 24 4
gpt4 key购买 nike

我正在尝试使用带有内置用户身份验证的 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);
}
}
}

最佳答案

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

关于c# - 如何在 ASP.NET MVC 5、Entity Framework 6 中使用流畅的 API 映射表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com