Base Class / Entity in EntityFramework 5.0

I am using Entity Framework 5 in the First database and I am using the edmx file.

Most of my objects have 6 common fields. Fields like CreatedAt , CreatedBy , etc. Now I have implemented some functions as extensions that can only be applied to the IQueryable those objects that have common fields. But when I implement the extension method, it can be accessed by any type of IQueryable , since it has typed T, and I can only determine that the type of T should always be of the same type.

So, I thought that I could give a base class to entities that have common fields and define type T as the base type. But it seems like I can't do it.

Any idea on how to solve this problem or implement what I explained above?

+7
c # asp.net-mvc entity-framework-5 asp.net-mvc-4 ef-database-first
source share
2 answers

Do not create a base class. Create an interface as shown below:

 public interface IMyEntity { DateTime CreatedAt { get; set; } string CreatedBy { get; set; } // Other properties shared by your entities... } 

Then your models will be like this:

 [MetadataType(typeof(MyModelMetadata))] public partial class MyModel : IMyEntity { [Bind()] public class MyModelMetadata { [Required] public object MyProperty { get; set; } [Required] public string CreatedBy { get; set; } } } 
+8
source share

I'm a fan of:

 public interface IShared { DateTime CreatedOn { get; set; } } public interface ISharedValidation { [Required] DateTime CreatedOn { get; set; } } public interface IMyEntity: IShared { // Entity Specifics string Username { get; set; } } public interface IMyEntityValidation: ISharedValidation { [Required] string Username { get; set; } } 

Then your models will be like this:

 [MetadataType(typeof(IMyEntityValidation))] public partial class MyModel : IMyEntity { public object CreatedOn { get; set; } public string Username { get; set; } } 

If T4 is generated by the Entity Framework, then your non-auto-generated class will look like this:

 [MetadataType(typeof(IMyEntityValidation))] public partial class MyModel : IMyEntity { } 

It is generally not recommended to use Bind in Asp.Net MVC.

+2
source share

All Articles