Best way to approach tying in Entity Framework 4 (

2019-04-10 03:30发布

问题:

I am a relative newcomer for C#.Net (.net 4), EF4, Winforms, and MVC3.

I had laid out a database in SQL Server in the process of developing a Winforms "backend" for a task I have been assigned. I setup a single Solution and created a .edmx from the database as its own project/assembly in the solution. Also in the solution is the winforms app that references the .edmx assembly. Using the default EF4 code generation, I built out the Winforms app and all is well there.

Now, I have to build out the enduser web frontend. I want to use MVC3. I have been through MVC3 tutorials on Pluralsight and fairly a decent understanding of MVC3 from that. But, both therein and elsewhere, most examples of MVC3+EF4 are "code first".

My confusion is what is the best approach to combine an EF4 Database-first with MVC3? I have looked some at EF4Templates, but, it seems these generate POCOs that are different than the default EF4 stuff and would break my Winforms app. I have read some on Repositories and the use of Automapper as well. I can add a reference to EF4 and my .edmx into the MVC3 project (same as I did with the Winforms), but it appears one still has to contruct a controller/view's model OR can one just work directly with the default EF4 classes in a controller?

Just seeking some guidance as to just how this has to be approached with respect to MVC3.

Thanks!

回答1:

You could work directly with the default EF4 classes in a controller if you wanted. The tooling support in the MVC 3 Tools Update for adding and scaffolding controllers works with code first but you can also use an existing context from a .edmx if you want to work directly with the objects.

http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

If you would rather use a repository pattern in your application you can check out the MvcScaffolding package, some info about it can be found on Steve Sanderson's blog.

http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/

You could also create view models yourself if you wanted to go that route.