Entity Framework 4.1 - Going crazy with the number of options - asp.net-mvc-3

I've built a site in MVC3 using EF 4.0 using the Repository pattern. Everything was going good but I'm starting to run into a lot of "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects" errors. It seems that my repository layer is getting the contexts all mixed up, so I figured it might just be easier to start a new EF4.1 project.
At first I looked into Repository Pattern + Unit of Work, but came across some threads saying that this isn't needed for EF4.1. I came across this thread saying "DbContext is implementation of unit of work pattern and IDbSet is implementation of repository pattern.". I figured maybe then I could just use that. Upon further inspection though it seems that DbContext uses the Code First approach, which as far as I can tell will drop and create the database again if the POCOs change. I need to keep the data in my database, so as far as I can tell that option is out.
My head is spinning right now with EF options. Is the Repository pattern needed with EF4.1? Is DbContext meant for working on databases that are already full of data? Is there a better way of managing the entity contexts that don't involve these?
Any push in the right direction would be great =/

A few comments. For details I recommend to do some basic research using a search engine.
...I'm starting to run into a lot of "The relationship between the two
objects cannot be defined because they are attached to different
ObjectContext objects" errors. It seems that my repository layer is
getting the contexts all mixed up, so I figured it might just be
easier to start a new EF4.1 project.
If you have this error you did something wrong. EF 4.1 won't protect you to do the same mistake again because you also cannot change relationships between objects that are attached to different DbContexts. You just have to analyze and debug your code and find the source of the problem.
...this thread saying "DbContext is implementation of unit of work
pattern and IDbSet is implementation of repository pattern.". I
figured maybe then I could just use that...
ObjectContext and ObjectSet<T> is an implementation of those patterns as well. This is no reason to change the version of Entity Framework.
Upon further inspection though it seems that DbContext uses the Code
First approach...
You can also use Database First and Model First approach with DbContext.
...which as far as I can tell will drop and create the database again
if the POCOs change. I need to keep the data in my database, so as far
as I can tell that option is out.
You can turn that feature off. Also, EF 4.3 has a migration feature which helps to update and evolve an existing database schema.
Is the Repository pattern needed with EF4.1?
No. It's also not needed for ObjectContext. To be precise, it's not needed that you write your own (abstract) repository of top of EF, because EF is already an implementation of that pattern.
Is DbContext meant for working on databases that are already full of
data?
Yes. The additional feature to create a database from code (Code-First) is mainly a productivity tool for the development phase of your application which is supposed to be disabled in production.

Related

NHibernate, Sessions, MVVM and Repositories

I am beginning to wonder if ANYONE uses NHibernate with a WPF or Win Forms application, such is the dearth of examples or text books on the subject. I am struggling to find "best practices" for its use, and especially session and sessionfactory management, with an MVVM WPF application and repositories.
To jump right in, it seems that the preference is to supply the repository with an ISession. But, where is this instantiated - in the ViewModel? - and if so, does this not created an uncomfortable dependency between the VM and NH (or is that just simply unavoidable, no matter how you dress it up?) Any implications for a multi-user application?
With the repository pattern - should I use one large repos. for all objects (and hence one session) or, as seems more manageable at first sight, should the repositories be split up in some logical business-related way? - but, if split up, how then to manage sessions? In my case, a form/window does not just deal with one entity (maybe it should...?) but with more than one. I don't want the ORM side to be dictated by the UI form design (maybe it should!?)
And then again, SessionFactory - where, and when to create it - once, at app startup?
Any good pointers or references for an NH app that is not web-based would be much appreciated.
Here is a reference to a similar question, but it was posed over four years ago: Using Unit of Work design pattern / NHibernate Sessions in an MVVM WPF
Many thanks
I've been using NHibernate with MVVM for years, once you get it going it's great. The MSDN article Building a Desktop To-Do Application with NHibernate covers the whole issue of session management rather well and is definitely worth a read.
One thing that will make life a lot easier is the use of a good dependency injection framework. I personally use Ninject and one of the things I particularly like is its support for object scoping. For example you can set your NHibernate session object (and thus the entity repositories) to scope to the pages in your application using InScope, so anything within the hierarchy of a given page that asks the injection framework for a session object will all get a pointer to the same instance.
Lots of other advantages to going down this route, for example it's very easy to use things like Castle Dynamic Proxy to inject property change notification to classes so that the entities you get back from your database queries support it automatically and thus can be bound to directly in the view or subscribed to by other class instances in your model or view model. Same goes for lists, which can be problematic because replacing a database entity list with an ObservableCollection<> can cause the database to think the entire list has changed which in turn causes performance problems when every single entity starts serializing itself back to disk regardless of whether or not it has actually changed.

Switch from Entity Framework Database First to Code First

Our Solution is currently based on Entity Framework Database First. We have a T4 Template that generates repository classes from the EDMX.
We are reviewing our planned approach for releasing changes, especially Database changes. If we continue with Database first, then we will need to separately generate scripts to change the development and other databases.
It seems that with Code First, we simply change the model and that generates scripts to change the various databases. This seems more straightforward, does not involve hand crafting scripting processes and lower risk.
So, if we make the switch, is it simply a case of:
Moving the previously generated models from EDMX in our Entities
Project to (they're all currently in one Class File) to (preferably
separate) Class Files in a folder within the Entities Project
Adjust the T4 Template to pick up the models from their new location
No longer using the EDMX and Update from Database
When we want to make a change to the model, simply changing the (previously but no longer generated) classes
Using Code First Migrations to implement changes to the Test and
other databases
Finally how would we see the relationships between the models? Is there a way of creating the diagram?
Thanks,
Chris
This is something I have done in the past. Over time I have tried many different methods. Currently I am using EF Reverse Poco Generator to allow changes to be made to the database and reflected in code and to initially generate the Model/Poco classes. I can also make changes to the existing classes manually. Then I generate migrations for each change.
The code-first model allows for the defining of navigation properties the same as you have now, so you can see the relationships through code and tools for visualizing class relationships.
If you want to see the database structure you can use the 'Database Diagrams' feature in MS Sql if that is what you are using. It is my impression that you are encouraged to use tools other than entity framework itself for visualizing database or class relationships. This allows the EF team to focus on Database code instead of complex UI integration with VS.
I personally I depend on Database Diagrams to check my class structure and the DB they output, but I find it natural to just look at the Poco classes. I haven't found any exceptional class diagramming tools.
All that being said, you are correct in your statements. Although I would start from the EF Reverse Poco generated classes from your existing db to give you that added flexibility. Point your T4 at those classes using reflection instead of XML parsing (Look at T4 Toolbox for output file management) to get you started.
Reflecting on assemblies is a sticky bit when you get started. You need to make sure you have the EF/Poco assembly compiled so it can be loaded in memory and reflected on by your T4. On rare occasions, depending on how you are loading the assembly, it can stop refreshing the assembly so you have to restart VS. I run across this a couple times a month, so it wasn't a deal breaker for me. Once I got it up and running it made sense.

Using the Entity Framework and ADO in a hybrid setting for transition?

We have an app in ASP.NET MVC 3 that, due to legacy and porting reasons, is written entirely using traditional ADO.NET for the data layer.
I am now tasked with adding some reporting to this website, and the reports can result in some extremely complicated queries.
Are there any pitfalls in using the EF Power Tools to reverse-engineer a code first model and using it side-by-side with our current ADO.NET model? Doing so would allow me to use LINQ for querying the data I need, greatly speeding up the time required to write each report. I would need to shut off data context initialization, as we have our current model do that, but are there any glaring risks or problems associated with trying to do this?
If it's of any relevance (I know EF 5 has a ton of new features), we are using .NET 4 and will begin moving to .NET 4.5 as soon as it launches.
I think this is a very sensible thing to do. You could also use a database-first model, which you can refresh whenever the database changes and which does not try to initialize a database.
Since you will use the context read-only you can optimize the query process by setting the MergeOption property of ObjectQuerys to MergeOption.NoTracking. This reduces overhead because the context will not track changes of the generated objects.
A problem might be that there is more maintenance if the database changes, but I think the absence of walls of boiler-plate query code for reporting on the old data layer far outweighs that.
One day :) you may even decide to use the EF model to display data that users want to filter in the UI and use the old data layer for CUD commands. (a bit like CQRS).

Looking for an MVC 3 + IoC for DI sample NTier empty solution stack

Has anyone created an empty solution stack for .NET (C#) that incorporates an IoC framework for DI using multiple projects?
I've struggled for months to create a good reusable stack that has:
MVC UI web app
Empty BLL project (will add real entities later)
Empty DAL project (will add real daab classes later)
Reference/Search data tier
Includes an IoC framework
Sample usage of DI in a Home controller that can reach all the way to the DAL thru the entity layer or to ref/search tier all thru interfaces
Must NOT set a hard reference of any concrete classes at the UI layer
I've attempted this a few times but I always get hung up at #6 and I'm missing something basic in the structure of the stack. Has anyone managed to do this and have a sample solution to show how it's structured? I can create stacks all day long and add a IoC framework, but completely fail at getting it structured so that no concrete references are added to the UI layer. How else can the interface/concrete resolution of objects take place?
Surely some of you scholars have nipped this in the bud, please share some of this enlightenment with me :-)
ps - I've read Mark Seeman's book more than once.. I understand the concept of Composition Root... but have never seen one in use in an NTier solution and have been unable to implement the theory successfully
What I am looking for is a fleshed out solution stack of multiple projects that can be used as a base to start from. One that implements the composition root successfully and can be used to teach the SOLID principles by doing instead of telling. A solution that brings it all to life. See this question for reference.
My Shuttle Wiki FOSS has some elements of what you are after:
http://shuttlewiki.codeplex.com/
Although not every concern is in its own proejct/assembly I have found that it is not worth the effort to tease them apart unless you are really going to use the relevant assembly somewhere else. That being said, it is still very easy to split them out as care has been taken to keep the concerns decoupled.
Scanned through some of the comments. My opinion is that no project structure or technique should be used to try and prevent or protect other developers from using certain classes. Junior developers have to learn the ropes at some stage and some quick code walkthroughs would pick up coding not consistent with what you are trying to achieve.
Take a look at mine:
using repository pattern, ninject, entity framework 6, ...
https://github.com/mesuttalebi/NTierCSharpExample

Is Entity Framework 4.1 is the best solution for a web application that is using almost 400 database tables?

Is Entity Framework 4.1 is the best solution for a web application that is using almost 400 database tables or it would best to make cutome data access layer with straight sql and sp?
The number of tables only affects EF initialization where "views" must be compiled when the context is used first time in the application - 400 is a lot and it will take a lot of time. This can be speed up by generating source code for views and adding these source codes to the project - views will not be compiled at runtime because compiled code will be part of your application but you must manually do this each time you change the model. For EFv4.1 this feature is offered in EF Power Tools CTP1. For EDMX the feature is offered in EdmGen command line tool.
Another impact on such number of tables in on development. Using 400 tables in single EDMX seems impossible so you will need multiple contexts with different sets of mapped entities. This can be complex task for application architecture because working with multiple contexts makes everything harder.
If you want to use code only mapping you must either write classes and mapping for 400 tables or you will again use EF Power Tools CTP1 which will generate them for you.
It is not impossible to use EF with 400 tables but it is complex and requires some experience.
Different people may have different views on it. Answer to your question is how you use EF whether it will be poco model or you are going to use edmx? EF performance depends on the number of records as well, so if you are using 10 tables and altogether they have 100 records then ef will perform better.
But still performance of ef on the basis of tables and records is a big question and it depends on various factors including your database designing whether it is properly normalised or not.
We do have more than 1000 tables, and we are using it (its a web app). You do not have to put everything in a single model, that would make it pretty darn hard to work on the model itself. And we are using Code Only approach, its in development yet, but everything works fine so far.

Resources