Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class/Entity in EntityFramework 5.0

I'm using Entity Framework 5 in Database First approach and I am using edmx file.

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

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

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

like image 324
Amila Avatar asked Aug 16 '13 14:08

Amila


People also ask

What is base entity C#?

The base entity is marked as an abstract class because you will never need to instantiate it. It simply serves as a base class for your actual entities. public abstract class BaseEntity<T> : IEntity.

What is include in Entity Framework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

What is Entity Framework MVC 5?

It is a data access framework which used to create and test data in the visual studio. It is part of . NET Framework and Visual Studio.


1 Answers

Don't create a base class. Create an Interface, like 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; }  
   }
}
like image 126
ataravati Avatar answered Oct 10 '22 18:10

ataravati