Understanding Entity Framework - entity-framework

I Googled to find tutorials and documentation on Entity Framework and read a couple of articles too. I referred to MSDN documentation also, but still I am not able to understand it clearly.
With a little that I followed is that:
(1) Each table along with rows are considered as a single unit.
(2) It provides a solution to sudden table name change without affecting the application.
(3) It reduces a lot of code.
Can someone explain me in a more easy way with illustrations? Please don't be too technical.

Check out:
Entity Framework Overview
Intro to Entity Framework with SQL Server
Beginner's Guide to Entity Framework (has lots of articles, videos, etc.)
It's rather hard to find something that's not too technical and just shows nice graphical representations.
But basically you have three "layers" inside an EF model:
the physical database model - what tables and columns do you have?
the conceptual model - the business objects / entities you want to work with (which can be very similar or quite different from your physical model)
the mapping layer that defines the mappings between those two worlds

Related

Can a project have two different EF data models that reference the same table?

I've system that has a primary data model to perform most of the work.
The model has quite a few tables and with performance in mind when I came to add an administrative feature to the application I decided to use a second separate data model.
All works well until my second data model needs to access a table that is also in the primary data model. Now, from digging around I can see this can cause problems.
The two possible workaround I've come up with are to either:
Put the data models in separate projects.
Use views / stored procedures for accessing the table in question when required.
Method 1 seems the simpliest but I'm concerned about whether there would be any performance loss. Method 2 seems a bit messy and takes the point out of using EF.
Before I plump for using method 1, is there an easier work around that I could use?
In the end I decided to put the two data models into separate projects and I've there hasn't been any slowdown that I've been able to notice (I've not done any benchmarking but it's passed the perception test).
In one of her online tutorials EF guru Julie Lerman says that you should put your data model in a separate project anyway, so I don't think this has been a bad workaround.
I am working with 2 models in the same project, because I connect to 2 different databases. I have put different namespaces using "Custom Tool Namespace" on *.tt files but it is not necessary. It generally works, but it cannot handle situation when the entity (table) with the same name is in both models. When you save one model the entity with the same name is deleted from the second model.

Entity Framework & Class Models in MVC

I'm new to the MVC way of developing applications and for the most part am enjoying. One thing I'm a bit confused about is the use of the Entity Framework. The EF usually (at least in my experience) defines multiple tables and relationships through the .edmx table. A couple of questions:
Why would I define a separate class file for a specific table if EF is building all of the classes that I need in the background?
From some of the validation approaches that I've seen, they want to define validation logic in the class related to a model for a table. If I'm using EF, will I have a .cs file describing the model and a .edmx describing that same table (in addition to its associated tables)?
If yes, how do you connect the .cs file to the .edmx definition so that CRUD flows easily from the EF?
Sorry if these seem like easy questions but I'm just trying to get my head wrapped around these fundamental concepts. Too many examples out there use only a single table where in my business, I NEVER write an application that uses a single table. There are always multiple tables in relation to each other with foreign keys. Thanks for your prompt responses.
For a tutorial that shows the use of partial classes -- in a Web Forms application but for MVC the same technique would be used -- see Adding Metadata to the Data Model in this tutorial:
http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-8
From your comment "The EF usually (at least in my experience) defines multiple tables and relationships through the .edmx table." it sounds like you are familiar only with Database First and Model First -- for an introduction to Code First and an explanation of the differences, followed by a series of tutorials with an MVC example using Code First, see this tutorial:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Good questions, Darryl. Here are my responses to your bullet points:
Defining separate model classes that match the data models that EF creates is generally a good idea for the simple sake of separating your data access "stuff" from your business model objects that will get used throughout your app. Some people don't like this approach because it creates some amount of overhead when it comes to mapping your entities to POCOs but, if you use a tool such as AutoMapper, the overhead is minimal. The benefit lies in you creating a layer of separation between you and your (likely) evolving data model.
You could define validation logic in a buddy class (just a partial class that sits along-side your entity) but that would mean that you would be using that entity across your app and some would debate that that isn't the best idea. The alternative method, as mentioned above, is to create your own POCOs to mirror the entities that EF creates and place your validation attributes on the POCOs.
I mentioned this in the previous item but the way to do this would be to define buddy classes. Give EF buddy classes a Google and you should find plenty of examples on how to do that.
Just to add to all of this, if you choose to create POCO classes that mirror your EF entities, tools like AutoMapper can handle fairly complex relationships when it comes to mapping classes. So, if you have foreign key relationships in your data model, AutoMapper can understand that and map your POCO classes accordingly (i.e.: You have an entity that has a 1-to-many relationship and a POCO with a list of objects to mirror that relationship.)
I hope some of that helps...

Conceptual questions on the ASP.NET MVC 3 and Entity Framework/MySQL interface

I have now decided to try out ASP.NET MVC 3.
My host provider, however, only supports MySQL and therefore I have to figure out how to use MVC 3 with MySQL.
I have also decided that I don't wanna do any SQL code if I can avoid it, and I would also like O/RM without too much effort. I understand that the Entity Framework will actually help me accomplish this to a large extent.
I have been trying to get into the various ways of using the EF, with the database first, model first and code first approaches supplied by the framework.
So far, I have not had much luck, and I find that the examples available all use very different approaches that confuses me a lot.
I might begin by asking for guidance on getting a few concepts right.
First of all, the Model (in MVC) is actually more like a ViewModel, that represents something (Users, Posts, etc.) in terms of Properties is more or less simple classes. I.e. the model is where the data from the database gets mapped to an object (the O/RM). Am I right?
A repository is a wrapper that encapsulates a specific way of retrieving data for the models. For instance, a DatabaseRepository or a FakeTestRepository.
Should I have a single repository in my MVC project, or a repository per database table, such that I have a UsersRepository and PostsRepository?
Should the repository be a model for itself, not a model at all, or tied to individual models (so that UsersRepository is part of the UsersModel)?
I have tried to use the EF's model first approach, and for a simple test I just have created an empty model and added the entities "Author" and "Guide" that are related by a one-to-many relation.
When I then, in Visual Studio 2010, "Generate database from model", I get the corresponding sql code. I want this database to be created in MySQL. How can I accomplish that?
Are there some code examples for MVC 3 with MySQL and O/RM where the creation of a small site is demonstrated?
Thanks.
Concerning EF Model First approach: take a look at this Tips & Tricks article. We have described this common situation in it (it is Oracle-specific, but dotConnect for MySQL contains the "Devart SSDLToMySQL.tt" template).
As for the rest of the questions - there is no definite answer. Choose the approach that suits you better.
In my point of view, you should try the code first. And as you said that your host only provides MySQL you can also use MySQL database as a database I personally use MySQL. Concepts are the same but logic is different you have to code it a different way. But from my point of view, you can use MySQL as a database service.

How do I create a stored procedure with Entity Framework?

I read an old MSDN Forums post about Entity Framework where Julie Lerman stated:
wrt Stored Procedures. This is even
better than what you are referring to.
Not only can you map to sprocs (both
in EF and in LINQ to SQL) or override
the update/insert/delete methods, but
in EF, there is coming a capability to
CREATE stored procedures right in the
mapping layer. Not create them and add
them into the db, but just have them
live in the EDM. So the sproc doesn't
have to exist in the db.
This is not in the March bits, but I
saw a demo of it last week and we will
have it in the next CTP.
I want to see a demo of how this works, but it is excruciatingly hard to jump into such a huge framework and all of its documentation, and discover how to look at a single feature. From best as I can tell, Entity Framework is not dynamic enough to support the scenarios I want, at least not yet, but there are features discussed for future versions of EF that fit my needs. For now I am using a hand-rolled query generator, since the ORM features of EF do not fit my needs and I really just want an awesome query generator and the ability to create stored procedures and serialize Parameterized Queries.
Bottom line: So how does Entity Framework create stored procedures "live" without them existing a priori in the database? Is it customizable? How does it handle changes to the conceptual layer? And why would the mapping layer own this logic? Or is Julie just referring to something gross like T4 Templates (YUCK!!!)?
Julie's post seems a little vague. If it's not in the DB, it's not a "stored proc" as most people know it. I don't think she meant generate a proc; I don't think you can do that today, and I know you couldn't do it in 2007. Nor was T4 in use in 2007.
She may have been talking about EdmFunction, but it's hard to tell. She's pretty active on Twitter, so you could just ask her what she meant.

Linq to SQL, Entity Framework, Repository Pattern, and Dependency Injection

Stephan Walters video on MVC and Models is a very good and light discussion of the various topics listed in this questions title. The one question listed in the notes unanswered was:
If you create an Interface / Repository pattern for Linq2SQL, does Linq2SQLs classes still cause a dependency on Linq, even though you pass the classes as toList?
It is probably an easy answer YES, however, what standard mechanic would you use to represent the data?
Lets say you have a Product entity that is made up of three tables (Prices, Text, and Photos) (you could have sets of price for different regions, different text for localization, and different photos). (Sounds like a builder pattern) Would you create a slice of these tables grabbing the right prices, text, and photos in to a single List? Since Lists may be proprietary, would you use a Dictionary object?
I thank you for your answers. I am very interested in the "standard and proper" way to do it rather than 101 possibilities.
Another quick question: is Entity Framework ready for a complicated database yet? There are a lot of constructs that Linq2SQL likes that EF does not. EF seems to require identity fields as primary keys (HAHA), but it seems like every demo does this. I want to use EF, but I constantly fail to make it work, falling back to Linq2SQL.
If you keep the L2S on the other side of the Repository facade (remember, that's all a Repository is - a facade) then you decouple the rest of your application from L2S. This means that the job of the code behind your repository is to turn the L2S into "domain" objects, custom classes, and then the Repository returns those.
In this sense, the Repository is returning fully formed "Product" objects with all their related Price, Text, and Photo data. This is called an Aggregate Root.
There shouldn't be a problem with Lists, since they are CLR objects.
As far as EF for advanced scenarios, my advice would be not yet, for the reasons you note.
The standard mechanism I'd use to represent the data is a Data Transfer Object. I would never return a LINQ to SQL or Entity Framework object across a service boundary, and I would hesitate to return it across a layer boundary of any kind. This is because these objects will serialize implementation-dependant data.