Currently I have created a Base Entity type that all my entities will derive from.
public abstract class BaseEntity
{
/// <summary>
/// Key Field for all entities
/// </summary>
///
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
/// <summary>
/// Date entity was created
/// </summary>
public DateTime DateCreated { get; set; }
/// <summary>
/// Last date Modified
/// </summary>
public DateTime DateModified { get; set; }
/// <summary>
/// keep track of Row Version used for concurrency
/// </summary>
1679178751
public Byte[] RowVersion { get; set; }
}
}
I am thinking of decoupling my model from entity framework so it is not reliant on it. I’d like to have another project that is for my EF implementation. So, I would like to include the mappings in that project that will make up the relationships in my model.
Since my BaseEntity class is an abstract class what is the best way for m开发者_如何转开发e to keep my [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] and [TimeStamp] attributes so that it will apply to all my derived entities using the fluent API and separate mapping file? I don't think I can setup the modeler to add the BaseEntity mapping becasue it is an abstract class. Should I create an interface that has all my base functionality and repeat the mappings for all my entities?
I am using the EntityTypeConfiguration class and creating separate mapping classes for all my entities.
You can use base class:
public abstract class BaseEntity
{
public Guid Id { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public Byte[] RowVersion { get; set; }
}
Now it depends if you want to have inheritance mapped or not. I guess you don't want so define your configuration like:
public class BaseEntityConfiguration<TEntity> : EntityTypeConfiguration<TEntity>
where TEntity : BaseEntity
{
public BaseEntityConfiguration()
{
HasKey(e => e.Id);
// This is not very good - check http://stackoverflow.com/questions/6098972/guid-comb-strategy-in-ef4-1-codefirst/6100606#6100606
Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(e => RowVersion).IsRowVersion();
}
}
Now for each entity derived from BaseEntity
derive its configuration from BaseEntityConfiguration
,
It is not a good practice for classes to inherit a base.
It is better to prioritize composition and deprioritize inheritance for these cases.
Therefore, you should include as one more attribute of each entity a class that represents the metadata with the attributes of the BaseEntity class.
GL
Source
精彩评论