gpt4 book ai didi

c# - 从 ASP.Net MVC 5 Identity 添加外键时出错?

转载 作者:太空宇宙 更新时间:2023-11-03 15:04:07 24 4
gpt4 key购买 nike

我有一个客户模型:

public class Customer
{
[Key, ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }

public string Title { get; set; }
}

这就是我的 IdentityModel.cs 的样子:

public class ApplicationUser : IdentityUser
{
public virtual Customer Customer { get; set; }

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}

ApplicationDbContext:

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

public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}

//new
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}

编写该代码后,我运行了enable-migrationsadd-migrations,然后是 更新数据库没有发生任何错误。

当我尝试创建一个带有 View 的MVC 5 Controller 时,使用 Entity Framework ,使用带有新数据上下文类的模型 Customer,我得到了这个错误:

enter image description here

怎么了?除了 ApplicationUser :IdentityUser 类和 Customer 类之外,我没有更改任何内容。

我对此很陌生,所以非常感谢非常详细的说明:)

最佳答案

尽管您没有发布 IdentityUserLogin、IdentityUserRole 等。我可以想象您没有为这些类定义主键。 Entity Framework 需要每个和 every entity to have a key .您可以按照约定命名您的主键属性 IdClassNameId 或使用数据注释,尤其是 Key。

更新

根本问题与外键无关,而是缺少主键。

首先,您不应该将一个属性同时定义为 Key 和 ForeignKey。从 UserId 中删除 Key 属性,只保留 ForeignKey。接下来像这样定义一个 Id 属性:

    public int Id { get; set; }

Entity Framework 足够智能,可以将其识别为主键。在您的所有实体中执行此操作,更新数据库,您就可以开始了。

关于c# - 从 ASP.Net MVC 5 Identity 添加外键时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44581981/

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