我正在使用 Asp.net core 和 EF Core 构建一个应用程序。我在使用代码优先概念执行时遇到以下异常。
'System.Reflection.CustomAttributeData' requires a primary key to be defined.
只有当我在 DBContext 类中使用 isUnique
定义 modelbuilder
时,才会发生这种情况。如果我注释掉整个模型构建器,一切都会正常。它创建数据库和表没有任何问题。
下面是我的 模型构建器
:
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
// Make unique properties
modelbuilder.Entity<Application>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<Domain>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<Roles>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<Environments>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<NetworkZone>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<Status>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<Type>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<OperatingSystems>()
.HasIndex(a => a.OSVersion)
.IsUnique();
modelbuilder.Entity<Servers>()
.HasIndex(s => s.ServerName)
.IsUnique();
modelbuilder.Entity<ResourceGroup>()
.HasIndex(a => a.Name)
.IsUnique();
modelbuilder.Entity<AccessType>()
.HasIndex(a => a.Name)
.IsUnique();
}
这是我在所有模型中继承的实体基
类。
public abstract class EntityBase
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
[Key]
public int Id { get; set; }
/// <summary>
/// Gets or sets the created by.
/// </summary>
/// <value>
/// The created by.
/// </value>
public string CreatedBy { get; set; }
/// <summary>
/// Gets or sets the create on.
/// </summary>
/// <value>
/// The create on.
/// </value>
public DateTime CreatedOn { get; set; }
/// <summary>
/// Gets or sets the modified by.
/// </summary>
/// <value>
/// The modified by.
/// </value>
public string ModifiedBy { get; set; }
/// <summary>
/// Gets or sets the modified on.
/// </summary>
/// <value>
/// The modified on.
/// </value>
public DateTime ModifiedOn { get; set; }
}
最佳答案
我通过更改下面的模型构建器以更正实体来修复它。
来自:
modelbuilder.Entity<Type>()
.HasIndex(a => a.Name)
.IsUnique();
至:
modelbuilder.Entity<Types>()
.HasIndex(a => a.Name)
.IsUnique();
Type
由系统使用,因此我的modelbuilder
中存在拼写错误
关于c# - 创建唯一属性时的主键异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204949/