我正在使用Asp.net核心和EF Core构建应用程序。在使用代码第一概念执行时,我得到的是异常。
' System.Reflection.CustomAttributeData'需要一个主键 定义
只有在我的DBContext类中使用modelbuilder
定义isUnique
时才会发生这种情况。如果我评论整个modelbuilder
,一切正常。它创建数据库和表格,没有任何问题。
以下是我的 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();
}
这是我在所有模型中继承的entity base
课程。
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; }
}
答案 0 :(得分:2)
我通过更改下面的模型构建器来修复它以更正实体。
从:
modelbuilder.Entity<Type>()
.HasIndex(a => a.Name)
.IsUnique();
为:
modelbuilder.Entity<Types>()
.HasIndex(a => a.Name)
.IsUnique();
系统使用了 Type
,因此我的modelbuilder