开发者

Should I use entity-framework classes or model classes in the Controllers?

I am new to entity framework and mvc.

I am trying to understand what a Controller should pass to the view.

Should it be the class from Models (MySolution.Models.Story) or the class from the entity framework (MySolution.Story).

The problem is that if I pick the one from entity framework, then the DataTypes and html-helpers are not working correctly. If I pick the class from models, then I can't convert from the entity class to the model class, for exampl开发者_如何学JAVAe:

TrendEntities TrendDB = new TrendEntities();
public ActionResult Details(int id) {  
  var Country = TrendDB.Countries.FirstOrDefault(c => c.CountryId ==id);  
  return View(Country);  
}  


Just use the adp.net entity framework POCO templates to generate. download the template. right click in the entity designer and select "add code generation item" and choose the poco template. Now your objects dont have all of the 'entity framework baggage' with them. Proxies are automatically created behind the scenes and you don't need to do any object mapping. You can find this template by adding a new item to visual studio 2010, and searching the online templates from within the add dialog for POCO. The template name is:

ADO.NET C# POCO Entity Generator


You are looking for either AutoMapper or ValueInjecter. These two libraries are "Object to Object" mappers, which are designed for mapping values from one object to another object. I have only used AutoMapper before. It is great and pretty easy to pick up. I've heard good things about ValueInjecter as well.


After some investigation, I figured out that I had a design problem. Long story short, REMEMBER that in MVC 3 we need a to define the following class in the model

public class StoryDBContext : DbContext
{ 
    public DbSet<Story> Stories {get; set;}
}

And then in the controller THAT's the one to use when accessing the Entity Framework.

In the previous version we were not defining the above class and were using the TrendEntities class (that was created by the framework) to access the DB. That's a bit confusing... So, in my example, TrendDB should be of type StoryDBContext instead of TrendEntities and things are working as expected.


Use a ViewModel. This is a class that you declare having the properties you want to display on your View.

For example:

var country = TrendDB.Countries.FirstOrDefault(c => c.CountryId == id);

CountryDetails details = new CountryDetails();
details.FirstValueToShow = country.Name;
return View(details);  

Remember to strongly type your Details view to the ViewModel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜