【问题标题】:If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating' .NET Keyless attribute Error如果您打算使用无键实体类型,请在“OnModelCreating”中调用“HasNoKey”。NET Keyless 属性错误
【发布时间】:2022-07-19 16:40:11
【问题描述】:

我正在使用 C# (.NET) 开发一个项目,我想进行初始迁移,但遇到了问题。我尝试了很多解决方案,但仍然出现错误。

AppDBContext:

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            object value = modelBuilder.Entity<Actor_Movie>().HasKey(am => new
            {  
                am.ActorId,
                am.MovieId,
            }
            );

            modelBuilder.Entity<Actor_Movie>().HasOne(m => m.Movie).WithMany(am => am.Actors_Movies).HasForeignKey(m => m.MovieId);

            modelBuilder.Entity<Actor_Movie>().HasOne(m => m.Actor).WithMany(am => am.Actors_Movies).HasForeignKey(m => m.ActorId);

            base.OnModelCreating(modelBuilder);


        }

MovieCategory.cs:

namespace eTickets.Data.Enums;

public class MovieCategory
{

}

错误:

PM> add-migration initial
Build started...
Build succeeded.
System.InvalidOperationException: The entity type 'MovieCategory' 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.
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)

 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
The entity type 'MovieCategory' 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.

让我知道我做错了什么。

【问题讨论】:

    标签: c# .net asp.net-mvc visual-studio


    【解决方案1】:

    在实体框架中,大多数实体都有一个唯一标识符来引用它们。错误消息表明您的 MovieCategory 类缺少这样的标识符。将Id 属性添加到MovieCategory

    public class MovieCategory
    {
      public int Id { get; set; }
    }
    

    如果您打算创建无密钥实体,请使用错误消息中描述的方法或使用 Keyless 属性标记类(来自 EF Core 5):

    [Keyless]
    public class MovieCategory
    {
    }
    

    更多关于无钥匙实体的信息可以在here找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多