Reputation: 1145
I am building an application with Asp.net core and EF Core. I am getting below exception upon execution with code first concept.
'System.Reflection.CustomAttributeData' requires a primary key to be defined.
This only happens when I define modelbuilder
with isUnique
in my DBContext class. If I comment out entire modelbuilder
, everything works fine. It creates database and tables with out any issues.
Below is my 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();
}
Here is my entity base
class that I am inheriting in all my Models.
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; }
}
Upvotes: 2
Views: 390
Reputation: 1145
I fixed it by changing below model builder to correct Entity.
from:
modelbuilder.Entity<Type>()
.HasIndex(a => a.Name)
.IsUnique();
to:
modelbuilder.Entity<Types>()
.HasIndex(a => a.Name)
.IsUnique();
Type
is used by System so there was a typo in my modelbuilder
Upvotes: 2