Can Entity Framework generate the DAL code? - entity-framework

I know that entity framework has a database first approach. Now the question is whether it can generate the DAL (data access layer) code (not the models) for me.

When using a Object Relational Mapper (ORM), you don't typically have CRUD code in the traditional sense. Rather, it abstracts those operations into more object oriented operations.
For example, you don't "insert", you add the model class to the table, then save changes. The ORM automatically generates the SQL needed to make the Object model match the data model.
So my point is, your question displays a basic lack of understanding of how ORM's work and how they relate to data models. You should probably do a little reading.

I'm not sure what you mean specifically by "DAL code", as that's a rather ambiguous term. I would consider your Entity types part of the DAL.
When you use a model-first or database-first approach, the Entity Framework tools can auto-generate a context class from your model .edmx, which will inherit from ObjectContext. It's easy to customize the generated context class with T4 templates by finding one online that already generates from a .edmx, and modifying to your liking.
Code-first development uses the DbContext, which is not typically auto-generated. Please see this post on Scott Gu's blog for more details on this.

Related

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...

Generate POCO classes and the mapping for an existing database using Entity Framework

Is it possible to auto generate the POCO classes and the mapping with the database defined separately using Fluent API (instead of annotations) for an existing database? Instead of coding all these entity classes manually, I find it easier if they are auto generated and then I can change them as required if the names are not incorrect (plural or singular) or the some of the relationships are not correctly mapped etc. This will save lot of time for me compared to coding all the entity classes and relationships from scratch and I am not that familiar with the fluent API syntax as well.
Yes, i encourage you to use Entity Framework Power Tools CTP1
Reverse Engineer Code First - Generates POCO classes, derived DbContext and Code First mapping for an existing database.
hope this helps
The Power tools are incredibly slow to generate files. It takes over an hour to work on my companies database (has a lot of tables).
Instead take a look at this visual studio extension http://visualstudiogallery.msdn.microsoft.com/ee4fcff9-0c4c-4179-afd9-7a2fb90f5838
It generates cleaner code, WCF serialisation classes, and includes the database default constraints as part of the POCO ctor.
Disclaimer: I should mention that I am the author of this extension

EntityFramework withour EDMX

We are about to start using EF as our ORM. We have our own MetaData representing the databse stracture and we will generate whatever we need off of that.
We are wondering whether to use the "old" EDMX approace, or to use the new EDMX free approach (wiht DbSet and DbContext). As we do our own code/edmx generation it seems odd to generate an EDMX and then generate objects and context off of it.
The thing is I don't see much talk about about the EDMX free approach. Is it being used by anyone? Can someone with experience share their impressions? Are there known limitations? Are there pros and cons?
Asher
Are you asking if anybody is using code-first? :) By checking the number of questions in entity-framework-4.1 and code-first and ef-code-first I guess people are using it a lot. There were several questions about code-first x non code-first. Some of I answered:
EF POCO code only VS EF POCO with Entity Data Model
EF Model First or Code First Approach?
EF 4.1 Code-first vs Model/Database-first
Generally there are four approaches:
Model first (database generated from EDMX)
Database first (EDMX generated from database)
Code first (database generated from code mapping)
Database first with code mapping (code mapping manually created for existing database or manually updated mapping generated by EF Power Tools CTP)
Selection of the approach usually depends on the way how you want to develop application (as described in linked answers). It also depends if you want to use ObjectContext API or DbContext API. The former one is usually used with first two approaches (but the secret is it should work with code-first as well) the later one with all of them.
Code first has some limitations - it doesn't support all mapping features EDMX does for example:
Stored procedures mapping (it doesn't mean you cannot execute SP when using code first)
SQL functions mapping
Advanced EDMX features like defining queries, query views, model defined functions
etc.
What I don't understand is why are you trying to combine your code generation tool with EF. Either use your stuff or use EF's stuff. You will avoid complications and incompatibilities.

Which variant of Entity Framework to use in WCF based enterprise app

We are in a process of designing an application with approx 100 tables and complicated business logic. Windows Forms will be used on the client side and WCF services with MSSQL on the server.
Custom DTOs are used for client-server communication, business entities are not distributed.
Which variant of Entity Framework to use (and why):
EF 4.0 EntityObjects
EF 4.0 POCO
EF 4.1 DbContext
Something else
Database-first approach is a requirement.
Also, is it worth implementing a Repository pattern? It seems a bit redundant, as there is one level of abstraction in the mapping itself and another one in the use of DTOs. I'm currently leaned towards using auto-generated extendable repositories for each entity returning IQueryable, just to have a place to put common queries, but still allowing querying entity model directly from the Service Layer.
Which variant to use? Basically once you have custom DTO the only question is do you want to have control over entities code (their base class) and make them independent on EF? Do you want to use code first? If the answers to all questions are no then you can use EntityObjects. If you want to have entities persistence ignorant or use custom base class you should go to POCO. If you want to use code first or new DbContext API you will need EF 4.1. Some related topics:
EF 4.1 Code-first vs Model/Database-first
EF POCO code only VS EF POCO with Entity Data Model (this was related to CTP)
ADO.NET DbContext Generator vs. ADO.NET POCO Entity Generator
EF Model First or Code First Approach?
There are more things to consider when designing service layer. You should be aware of complications you will have to deal with when using EF in WCF. Your service will provide data to WinForms application and it will work with them in "detached mode". Once user will do all changes he wants to do he will post data back to the service. But here comes the problem - you must tell EF what has changed. If you for example allow user to change order with all its order items (change quantity in items, add new items, delete some items) you must say EF exactly what has changed, what was added and what was deleted. That is easy when you work with single entity but once you allow user to change object graph (especially many-to-many relations) then it is quite tough. The most common solution is loading the whole graph and merge the state from incoming DTOs to loaded and attached graph. Other solution is using Self tracking entities instead of EntityObjects/POCOs + DTOs.
When discussing repositories I would refer you to this answer which refers many other answers discussing repositories, their possible redundancy and possible mistakes when using them just to make your code testable. Generally each layer should be added only if there is real need for the layer - due to better separation of concerns.
The main advantage of POCOs is that those classes can be your DTOs, so if you've already got custom DTOs that you're using, POCO seems a bit redundant. However, there are some other advantages which may or may not have value to you, since you didn't mention unit testing as a requirement. If you plan to write unit tests, then POCO is still the way to go. You probably won't notice much difference between 4.0 POCO and 4.1 since you won't be using the code-first feature (disclaimer: I've only used 4.0 POCO, so I'm not intimately familiar with any minor differences between the two, but they seem to be more or less the same--basically I was already using POCO in 4.0 and haven't seen anything that's made me want to update everything to use 4.1).
Also, depending on whether you plan to unit-test this layer, there's still value in implementing the repository/unit of work patterns when using Entity Framework. It serves to abstract away the data access logic (the context), not the entities themselves, and allows you to do things like mocking your context in unit tests. What I do is copy the T4 template for my context and use it to create the interface, then edit the T4 template for the context and have it implement that interface and use IObjectSet<T> instead of ObjectSet<T>. So instead of:
public class MyEntitiesContext
{
public ObjectSet<MyClass> MyEntities
...
}
I end up with:
public interface IMyEntitiesContext
{
public IObjectSet<MyClass> MyEntities;
}
and
public class MyEntitiesContext : IMyEntitiesContext
{
public IObjectSet<MyClass> MyEntities
...
}
So I guess it really comes down to whether or not you plan to write unit tests for this layer. If you won't be doing anything that would require mocking out your context for testing, then the easiest thing to use would probably be 4.0 EntityObjects, since you aren't planning to pass your entities between layers and it would require the least effort to implement. If you plan to use mocking, then you'll probably want to use POCO and implement repository/unit of work.

What are each of the template types intended usage, pros and cons?

I have not hardly touched EF4, but I've used Linq to sql quite a lot. I would like to start into one of the EF templates but I have no idea what situations make sense for each or what their intent was.
I have the following possibilities:
Data templates
ADO.NET Entity Data Model
Service-based Database (is this even related to EF?
Code templates (I am familiar with T4)
ADO.NET EntityObject Generator
ADO.NET Self-Tracking Entity Generator
Online Templates
ADO.NET C# POCO Entity Generator
I have no idea what situations make
sense for each or what their intent
was
Not meaning to sound rude, but did you have a look on MSDN/ASP.NET to find out? There is plenty of information around. And there is a lot to each of those templates, more than i can go into here. There is a MSDN page for each of these.
That being said, i'll give you a quick summary, so people who stumble here have some info.
ADO.NET Entity Data Model
This is the file you create to use Entity Framework as your ORM, and it is mandatory for using EF. You need this before you use any of the others. You can create your EDM with a number of different approaches, including database-first (generate from DB), code-first, model-first, etc.
Service-based Database
I have never heard of this term, and given i've been working with EF a lot lately (and reading), i doubt this will be related to EF.
ADO.NET EntityObject Generator
Generates classes for entities which inherit from the EntityObject class. Identical to the default EF code generator, except instead of putting output code into the Model.edmx.designer.cs (default) file, the code gets put into seperate files. I personally don't see any benefit in this template.
ADO.NET Self-Tracking Entity Generator
Generates classes for entities when you want to develop N-Tier applications (ie if you wanted to allow a WCF/Silverlight app to work with your model). Entities are setup to be 'trackable' by the EF Graph, in order to handle persistence operations from various applications.
ADO.NET C# POCO Entity Generator
My favourite. :) Generates classes for entities which inherit from nothing. They have no idea that they are being used for persistence. Use this for applications when you want persistence-ignorance, testability and loose-coupling of your domain/persistence layers.