asp.net mvc Core 网页错误提示:An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。

发布时间 2023-10-05 14:02:57作者: 秋痕无声

网页错误提示:

An unhandled exception occurred while processing the request.

InvalidOperationException: The entity type 'IdentityUserLogin<string>' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

翻译:无效的操作异常:实体类型“IdentityUserLogin<string>”需要定义主键。如果您打算使用无钥匙实体类型,请在“OnModelCreating”中调用“HasNoKey”。有关无钥匙实体类型的更多信息,请参见https://go.microsoft.com/fwlink/?linkid=2141943.

解决办法:

打开项目的Data文件夹下的ApplicationDbContext.cs,添加如下方法

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  //调用基类的OnModelCreating方法,设置数据库其它表和实体的映射关系
  base.OnModelCreating(modelBuilder);

  //InvalidOperationException: Unable to track an instance of type 'Article' because it does not have a primary key. Only entity types with a primary key may be tracked.

  //无效的操作异常:无法跟踪类型为“Article”的实例,因为它没有主键。只能跟踪具有主键的实体类型。

  //解决方法:如下,给实体类Article添加主键

  modelBuilder.Entity<Article>().HasKey(c => new { c.ArticleId });

  //同理,给实体类Column添加主键

  modelBuilder.Entity<Column>().HasKey(c => new { c.ColumnId });
}