Best practices to perform CRUD operations on Entities (Entity Framework)

asp.net-mvc c# entity-framework

Question

I am trying to figure out where should I put database operation for each entity. Before this confusion, for each entity, I was doing all these database operations in a provider class. Provider class means that each class has a provider. Such as:

class Member
{
   public string FirstName;
   public string LastName;
}

class MemberProvider
{
  //Singleton
  //Do database operations

   ......

   public List<Member> GetItems(FirstName = null, LastName = null)
   {
       // run store procedure
       //this returns List<Member> if any
   }

   public Member GetItem(int? Id = null,FirstName = null, LastName = null)
   {
       // run store procedure
       //this return Member if any
   }

   ....
}

then when I need a list of member with some filtering, I do this:

 List<Member> members = MemberProvider.Instance.GetItems(FirstName = "John", LastName = "Black");

The question is how can I do all this database operations related to entity in the entity itself ? Is it good practice ? What should I read to understand this concept ?

Thanks in advance.

1
3
1/22/2013 1:39:14 PM

Accepted Answer

In most cases, business objects and data access should be separated. Have a look at the Repository Pattern here, and here. This is probably exactly what you need.

5
5/23/2017 12:12:27 PM

Popular Answer

I would suggest to use Repository pattern. Here you are really good posts to get good introduction and sample code : Using Repository and Unit of Work patterns with Entity Framework 4.0

and another Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow