What is the best approach when trying to use POCO with EF4? - entity-framework-4

I have read here 3 approaches towards implementing POCO with entity framework namely
Create edmx model and turn off code generation so the model will not create heavy entities for you. Then you will create your POCO classes which have to follow some restrictions.
You can use the POCO template which can be downloaded to VS 2010.
Use Code First approach where you code your POCOs and you define mapping in code. To do
this you need EF 4.0 Feature CTP from here.
I was personally going to opt for the second approach as it is quicker but what are the things that I should keep in mind since it derives from ObjectContext I guess it is in a way coupled? I know the third approach gives the most flexibility but is it worth it ? Please share your thoughts regarding this..Thanks!

That link you have provided for "POCO Template" is broken - but i assume you mean this:
http://visualstudiogallery.msdn.microsoft.com/23df0450-5677-4926-96cc-173d02752313
This template can (and should) be used in conjuction with Option 1 you have stated.
That's what i use in my current application:
1 - Create EDMX Model
2 - Turn off code gen
3 - Use POCO Generator to generate POCO classes
The POCO's do not derive from anything - they are pure POCO's.

I found these two links to be invaluable when setting up my model/poco classes. Poco generation and Poco options. As mentioned above it is a good idea (certainly if using the repository pattern) to turn off code generation in the edmx and create both a derived ObjectContext class and your Poco classes via the two T4 templates provided by Microsoft.
If you use the T4 templates without making any changes to them then you will get a set of Poco classes with the "Change Tracking Proxies with Fixup" option enabled in the generated code.

Related

Generate model classes from Entity Framework for MVC2

I am following Steven Sanderson's "Pro ASP.Net MVC2 Framewok", which uses Linq2SQL. He uses abstract factory approach to support unit testing and mocking, and writes model classes in a separate project to facilitate this.
I am using Linq to Entity Framework instead of Linq2SQL, and I have built an entity model in EF from an existing database. (I am new to all of this).
I don't quite understand if I'm getting this right, but I beleive I should still generate model classes defined outside of EF (a layer between EF and presentation?), even though I could just pass Linq2EF query results entities directly in as MVC's models (security? separation of concerns?).
So I'd like EF to stub the model classes for me instead of hand-coding them all from scratch. Is there an easy way to do this, or am I mis-interpreting what I need to do?
Take a look at this blog great resource on this subject.
If you are going to use ViewModels I highly recomend using AutoMapper from souceforge

EF CTP5 which code generation item to choose?

With EF 4.1 on the way and CTP5 being available for few months now I've decided to try out the new functionality. As I see, there are multiple generation items available (DbContext and three different ObjectContext's). I also noticed they are not interchangable - I was first using the POCO ObjectContext in one of my app and today switched to DbContext and my entire repository broke. It was based on LoadProperty() methods, DeleteObject() and AddObject() methods and those are all missing on DbSet class which is used in DbContext generation.
I know there's a great blog series here http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx introducing the new functionality but it never really says when to choose what.
My requirements are:
ASP.NET MVC application, so lazy
loading mostly won't work coz at page
render it will say that context has
already been disposed (that's why I
need easy support for explicit
loading - in EF4 I did it via
Include(), using POCO context I did
it through LoadProperty() and now
in DbContext I believe I will use
the strongly typed Include()).
We probably won't be needing code-first
features (but you never know).
Difference between those two is mostly in API and feature set. DbContext of course have Include for query and Load but you will find it elsewhere. Moreover when using CTP5 assembly you will have strongy typed Include for both ObjectSet and DbSet (available on IQueryable interface as extension method).
Explicit loading (equivalent to LoadProperty) is performed by Load method on DbReferenceEntry<T> or DbCollectionEntry<T> - check Explicit loading related entities. It works even better then LoadProperty because you can define filter for loading.
You are starting with the wrong assumption that you can't use lazy load with MVC.
If you manage the context at a higher level, you'll be able to do that without problems.

SubSonic 3, Entity Data Model (Entity Framework) or LINQ to SQL for ASP.NET MVC development?

Having used all of them (some more than others), I am still undecided on which could be the best to use (with .NET 3.5). What are the pro's and con's of each when developing?
SubSonic 3
Not enough samples/documentation (I know its a wiki and people can update it, but it can be tricky to track things down - e.g. where are the sample apps (WebForms, MVC (current version, rather than pre-3), WinForms)). Text Templates didn't work as expected when I first tried them. For example, it does not clean up the table names like SubSonic 2 did (removing/replacing spaces for example). Also, you cannot say which tables to include, just the ones you can exclude (in ActiveRecord.tt). Context.tt and Structs.tt generates code for all the tables (you would probably not want the 'aspnet_' ones, and probably some others (session tables) as well).
Saying that though (hope I'm not being too harsh), it is quite a good ORM to use, minor issues aside.
Entity Data Model (Entity Framework)
Visual Designer for setting up models. Syncs with database, might be considered a bit 'verbose' and hard to understand. There is fairly decent documentation though. Not gone that much further in depth though.
LINQ to SQL
Also has a designer for creating models. Simple to use. Less features than the other two. I also had to apply a hotfix for an obscure bug (wouldn't update when the model had foreign keys that were not of type int)
NHibernate
Looked at this in the past, but not that easy to set up compared to the above.
Any sample ASP.NET MVC apps using this?
Ideally I would want a framework that:
a) could generate the models from a database
b) support LINQ syntax
c) retrieve only the data that is needed (e.g. for paging)
d) allow data annotations
e) could generate the sql to update or create new tables in an existing database
MVC is presentation layer, ORM is Data layer
I don't think that ORM has anything so much to do with an MVC application. At least if you tier your application properly. Model in an MVC application is rather model of the presentation layer view. A view model through which controller and view communicate. Not necessarily data model. MVC project template is a bit confusing, since developers think that MVC model = data model. In any business application that is not completely trivial (like a single assembly simple application) this is not equal. And it's better that its not. Especially if we take into cosideration separation of concerns. We shouldn't rely on particular ORM classes in any layer other than data layer.
But if you intend to use DTOs in your MVC application (as view models) I suggest you use that ORM that creates partial classes, so you can easily add additional stuff on them (like attributes). Your data annotations can be written inside of a special metadata class that can be attached to your model class by a single class-level attribute.
Suggestion
But I suggest doing something else. Use a separate layer with POCOs that will be used on all layers and would have data annotations on them. This will make your presentation layer independent of data layer and your POCOs may also be presentation optimised (like having a class called UserRegistration for instance with two password properties - with repeated value as well). Your repository in your data layer would be responsible for POCO conversion so all layers will exchange data using POCOs only instead of using data objects.
ORMs and class generation
With Entity Framework you do get a very controllable environment to generate your classes from a data store schema. Unfortunately it's not the same with others. Generateion is not all-in, but can be controlled and manipulated manually as well (if you'd like to do TPH/TPT structures).
Similar with LINQ to SQL. I haven't used any other ORM but I guess LinqConnect may have it's own editor similar to EF Visual Studio editor, because I've been working with MySql connector from the same company and I've used their designer for entities because it was better than the one provided with Visual Studio 2008.
But you have tools that provide code generation (and you can get templates on the internet for various ORMs as well):
there's T4 built into Visual Studio that can generate code for you; You can as well fint templates for ORMs written in T4 that you can then easily customize. Or write your own acording to your needs (I've written enumeration generator from DB lookup tables in the past)
MyGeneration is open source and you can find lots of templates for it
CodeSmith is not free but is a proved product that I've used in the past with .netTiers template (before we had LINQ) which saved lots of time and worked perfectly

Entity Framework 4 website architecture

Hi I've been given the task of creating an N-Teir website using the Entity Framework 4 and am coming up against some brick walls, more than likely in my knowledge.
My plan so far was to have these layers
Website (application layer),
What I'm calling Name.Framework (BLL),
Name.Data (DAL),
Name.Entities (contains POCO classes and other struct classes used in website/bll,
Name.Common (utility class)
I've tried to use the repository class, but am struggling to make things work how I thought they would. Below are a few examples of what I'm getting stuck on.
If I want to use .include() would this be in my Repository or is this the responsibilty of the business layer? (and I have no idea how this would work in the BLL)
Same question for .Order()? As I understood it this would need to be in repository or at least passed into the repo in some way?!?
Should I be using the BLL to pass in the Context to the repository/data layer? At the moment when I get an entity from the Data layer any navigation properties that weren't referenced in the repo just come back with 'Object Context Disposed', should the Business layer still hold the context etc so that this wouldn't happen?
Or to summarize this HELP!!!
I need to have this in some sort of order by tomorrow (eek!) as the project leader wants to know if we are going to continue with Entity Framework or move to NHibernate as in-house we have more knowledge of it.
Thanks for any help or suggestions
Matt
Looking for something similar myself I found this. Not looked into it too much at the moment but looks promising.
I'm currently working on a web hobby project with EF4 Code-Only, where I have the following structure ([name] being the name of my project):
[name].Web - An ASP.NET MVC 2 project
[name].Web.Models - Custom view models, along with AutoMapper mappings from my entity objects
[name].Models - My POCO classes, and interfaces for repositories
[name].DataAccess - Some interfaces related to data access, for example IUnitOfWork
[name].DataAccess.EF - All Entity Framework related classes and interfaces
I also have a test project for each of the above, plus a couple of projects with helpers and extensions for the tests.
It might be relevant to mention that part of the purpose of this hobby project is for me to learn how to use EF4 with some design patterns of my own choice (the ones that concern EF in this project are the Repository Pattern and the Unit of Work pattern). Another partial purpose is to build up a code base that I can re-use in later projects, and this has affected the division between projects in my application - for example, if I wasn't concerned with re-use, I'd probably have all data access related classes in one project instead of two.
I've implemented a basic EF, poco, Repository, UnitOfWork architecture largely following this article here:
http://devtalk.dk/CommentView,guid,b5d9cad2-e155-423b-b66f-7ec287c5cb06.aspx
I found it to be very helpful in these endeavors. Don't know if it helps you but others might be interested in the link.

How can I extend the Model in ASP.NET MVC and Entity Framework?

In my first ASP.NET MVC applications, the model was a simple O/R mapping between a table and the classes, managed by the Entity Framework.
Now I would like to add some meat to this skeleton, and introduce business methods for the generated classes. What is the recommended approch to this in ASP.NET MVC (with Entity Framework)? My favorite would be solution which also can be used in a service layer, with no ASP.NET MVC references, so that the same domain logic also could be reused in a desktop client.
Technically, I think it should be possible to extend the generated classes in a way which preserves the additional business logic even if the O/R classes need to be refreshed. (This is more a question related to the Entity Framework however.)
Edit: Many thanks for the contributions, and the information about the next version of Entity Framework (4.0). Building two sets of classes, one auto-generated to represent the data in the persistency layer and one for the actual business logic sounds interesting.
Within MVC.Net, the model is the least clearly defined part. In my opinion, it's basically the rest of your application (i.e. anything not related to the View or the Controller). The O/R Mapping part of your application should probably be outside of the "Model" also, as this is more of a data layer. The Model, should really deal in business objects and create views of your data to pass to the View.
There are lots of differing opinions on this, but I think it's best not to think of MVC.Net as traditional MVC Architecture.
If you are using EF v1.0 right now, the Entity Framework is very intrusive into your application, which means that you cannot create POCO very easily. The way you can extend your model is by using the partial class. So when you refresh your model, the partial class you did will still be valid. The Entity Framework team realizes this is a problem , and have improved this in next version (EF V4.0).
NHibernate is much more friendly and allow you easily extend your business logic.
I really think this blog post by Jeremy D. Miller is very good at pointing out the problem.
Abstract your Business Layer out into another project, then pass an instance of it onto your mvc controller using something like structure map. You can then call this Business Layer from your controller to retrieve your business entities (Model) and pass them on to the UI. This will allow you to resuse your Business Layer in your desktop application.
Not only meat but also some clothes and a style could be added to this project to make it seem chic. It depends on the time you have for the project. If you have time, I could suggest you to get a look to TDD and the frameworks that could be used with TDD such as Castle, NUnit, Moq etc.
As you mentioned a service layer is a must for any project but with these kinds of frameworks you could design your architecture more robust.

Resources