Domanda

Attempting to create an MVC project using EF and the Model first approach.

In order to implement it in a way that the Web and data portions are loosely coupled I'm attempting to implement the repository pattern, but, after reading many articles I'm still trying to grasp what objects my Repository interface should return or how they should bind/map to the 'M' model in my MVC project.

Here's a very simplistic example of what I'm asking.

//Repository Interface
public interface IMemberRepository
{
    Member GetById(int id);
    IEnumerable<Member> FindByName(string name);
}

//Repository Interface Implementation
public class MemberRepository : IMemberRepository
{
    //My DB Context object created by EF
    private MyContainer context;

    public MemberRepository(MyContainer context)
    {
        this.context = context;
    }

    public Member GetById(int id)
    {
        return context.Members.SingleOrDefault(x => x.Id == id);
    }

    public IEnumerable<Member>  FindByName(string name)
    {
        return context.Members.Find(x => x.name == name);
    }

}

So using Ninject as my DI framework I could call this from my controller as follows:

public class GroupsController : Controller
{
    public ViewResult Find(string name)
    {
        IMemberRepository repo = 
          ObjectFactory.Instance.CreateInstance<IMemberRepository>();
        return repo.FindByName(name);
    }
 }

At this point I'm just not understanding how my Member object (from the EF model) is supposed to bind/map to my 'MVC' member model object. It seems I must be missing some sort of mapping layer or I'm just completely off track. If I were to reference my EF generated class directly it feels like I'm negating the point of using an interface and DI framework. Any advice or direction at this point would be appreciated.

È stato utile?

Soluzione

Your IMemberRepository interface and its implementation MemberRepository look right to me. That is how I structure my database code as well.

Moving to the MVC world, I would create view models which you populate from your data model. This will give you the flexibility of adding any attributes or additional properties that you need in your view.

This would be the workflow:

  1. Fetch object(s) from repository
  2. Populate view model objects with all the data from your repository object(s)
  3. Return the view model to your view from the controller
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top