Reputation: 3301
We have an existing database where each of the entities has an Id like UserId, CustomerId. I am trying to introduce a BaseEntity class like so:
public abstract class BaseEntity : IEntity
{
public int Id { get; protected set; }
}
This way I can access the Id property for any entity without having to know what it's called. However this is causing us issues in the way we build out DbContext. We are getting errors complaining about the Id property as it doesn't exist on the db table. When we try to ignore it we get other errors like this:
You cannot use Ignore method on the property 'Id' on type 'xxx' because this type
inherits from the type 'xxx.BaseEntity' where this property is mapped. To exclude this
property from your model, use NotMappedAttribute or Ignore method on the base type.
However when we try to ignore the BaseEntity like so:
modelBuilder.Ignore<BaseEntity>();
However we then get the error:
Invalid column name 'Id'.
Clearly I am missing something quite obvious but any help would be appreciated. Basically I want the Id property to be completely ignored by the EF DbContext as the way we are using it is outside the context of the DB.
EDIT:
It looks like if I call:
this.Ignore(e => e.Id);
For every EntityTypeConfiguration then it works but I was hoping for a more generic solution, I tried creating a base configuration like so:
public abstract class BaseEntityTypeConfiguration<T> : EntityTypeConfiguration<T> where T : class, IEntity
{
public BaseEntityTypeConfiguration()
{
this.Ignore(e => e.Id);
}
}
But I get this error again:
You cannot use Ignore method on the property 'Id' on type 'xxx' because this type
inherits from the type 'xxx.BaseEntity' where this property is mapped. To exclude this
property from your model, use NotMappedAttribute or Ignore method on the base type.
Using NotMapped on the Id property on the base class does work but I was hoping to do this with the fluent api. Any suggestions?
Upvotes: 1
Views: 1904
Reputation: 836
We define it like this in the Base Class
[NotMapped]
public abstract TId Id { get; protected set; }
and then in inherited Entity
public override int Id {
get { return AssessmentID; } protected set { AssessmentID = value; }
}
[Key]
public int AssessmentID { get; set; }
Upvotes: 1
Reputation: 118937
You only need to ignore the property, not the entire class:
modelBuilder.Entity<BaseEntity>().Ignore(e => e.Id);
Upvotes: 0