Entity Framework in .NET 4

Entity Framework in .NET 4

Rate This
  • Comments 32

The Entity Framework in .NET 4 has a lot of new features and enhancements.  We got a lot of great feedback from you on the initial release of the Entity Framework (EF).  Let’s take a look at some of the things coming in new with Entity Framework 4.

Foreign Keys

Entity Framework now includes support for foreign keys.  Foreign key associations allow you to include foreign key properties on your entities, simplifying a number of key scenarios including data binding and n-tier development. Foreign keys can be used to setup entity relationships using foreign key properties directly:

 

    using (BlogEntities ctx = new BlogEntities()) {

        Post myPost = new Post {

            PostID = 102,

            PostName = "Post Title",

            CreatedDate = DateTime.Now,

            PostContent = "Post Content",

            BlogID = 11

        };

        ctx.Posts.AddObject(myPost);

        ctx.SaveChanges();

    }

 

In this example, even though the Blog object with BlogID == 11 was never loaded, we were able to connect our new myPost object to it directly.

 

Lazy Loading Support

Entity Framework now includes support for lazy loading.  When you create a new model in VS2010, entities that offer lazy loading are generated for you.  Lazy loading, which is enabled by default, doesn’t load each object returned by a query until you actually use it.  For instance, lazy loading means that each post in the below snippet isn’t loaded until it’s actually used to print out the post’s PostName property.

 

    using (var ctx = new BlogEntities()) {

        foreach (var b in ctx.Blogs) {

            Console.WriteLine(b.BlogName);

 

            //Note that we don't explicitly load the posts for the current blog,

            //the EF does it 'lazily' for us.

            foreach (var p in b.Posts)

                Console.WriteLine(p.PostName);

        }

 

    }

Plain Old CLR Object Support

EF4 now includes Plain Old CLR Object Support (POCO) support for entities.  This offers better test-driven development and domain-driven design support by allowing you to have no EF dependencies for your entities.  EF will still track changes for POCO entities, allow lazy loading, and will automatically fix up changes to navigation properties and foreign keys.  You can find out more about POCO support in the walkthroughs posted on the ADO.NET blog.

Text Template Transformation Toolkit Code Generation
In the first version of the Entity Framework, code generation didn’t allow for deep customization and wasn’t integrated into Visual Studio.  The Entity Framework now leverages Text Template Transformation Toolkit, or T4, which makes customizing code generation easy, flexible and powerful.  The experience is fully integrated into Visual Studio.  Built-in code generation strategies can be chosen by right clicking on the Entity Framework Designer surface and selecting ‘Add Code Generation Item…’:

Add Code Generation 

You aren’t limited to using the code generation strategies that ship in VS 2010; you can now write your own T4 templates or modify the default templates to provide your own code generation experience. 

Better N-Tier Support

An n-tier design allows you to separate data, business logic, and interaction layers to ensure data integrity and promote maintainability at each tier.  The Entity Framework team received a number of requests for improvements on n-tier support.  They’ve taken this feedback and made improvements to the API to allow for n-tier design, as well as a code generation template that generates objects with built in n-tier features, such as change tracking.  The template generates your entities as a set of CLR classes with Windows Communication Foundation (WCF) serialization attributes in place so they can easily be used in conjunction with WCF services. 

Generated SQL Improvements

We’re constantly trying to improve the readability and performance of the SQL we generate.  Numerous simplifications and improvements of the SQL generated when querying using the Entity Framework have been made in EF4.  One such improvement is the removal of some extraneous joins.  Another is the use of database wildcards for WHERE clause string parameters.  For instance, the following LINQ query will translate into a query that uses a WHERE clause with a LIKE statement and the ‘%’ wildcard to search for all Blogs whose BlogName property begins with “Visual Studio”:

 

    var query = from b in ctx.Blogs

                where b.BlogName.StartsWith("Visual Studio")

                select b;   

 

While these changes may seem small, improved SQL generation can result in queries that execute more quickly and put less load on your SQL Servers and network.

Enhanced Stored Procedure Support

Many databases contain stored procedures that perform custom SQL processing.  Entity Framework allows you to create a function in your entity model that calls a stored procedure through the Function Import feature.  The Function Import feature can now detect the columns returned from a stored procedure and create a corresponding complex type. In addition, existing complex types can be updated when a stored procedure definition changes.  Below, the Entity Framework Designer stored procedure wizard steps you through the process of importing your stored procedures as functions:

Add Function Import 

Entity Framework 4 offers these and other new features to increase developer productivity.  Share your thoughts and ideas with the team on the project forum, connect with the Entity Framework team on their team and design blogs, and check out videos and screencasts on Channel 9.

Namaste!

Leave a Comment
  • Please add 4 and 8 and type the answer here:
  • Post
  • Is this available in VS10Beta2?

  • Can you mkae it so that in the edmx designer you can remove non-nullable fields from your model?

    This is EF's biggest problem for me right now. It forces me to use almost every column of a table in my model's entities even if I never need them.

    Often I only want to update a few fields are query. I realize not having the fields present in the model stops INSERTS but for many scenarios that's fine.

    Can't we create non INSERTable entities in our model?

    You can remove them from the edmx's XML amnually but when you update from the DB again they'll all come back.

    Can this be worked on please?

  • @Andy - all of the features Soma mentions are available in the Beta 2 version of VS2010.

    @Bill - if those non-nullable fields are default or calculated values in the db, you can mark them as StoreGeneratedPattern="Identity". Currently this is another manual change in SSDL which gets overwritten with an update, however watch for this to be tied to the newly exposed StoreGeneratedPattern attribute in the designer properties at RTM.

    hth

    Julie

    (and thanks for the blog post, Soma!)

  • Minor nit but ...

    CreatedDate = DateTime.Now should be CreatedDate = DateTime.UtcNow

    Non-UTC times in a database are nearly always a bad idea.

  • @Julie Lerman

    If setting StoreGeneratedPattern="Identity" on a field allows it to be removed from the conseptual model and that property is exposed from the designer  then that indeed may be what I want.

    Thanks for the info Julie.

  • I have a 3rd party tree view control that seems to only like DataTables as the source.  I've not been able to make a stored procedure return a DataTable using Entity Framework. Is it possible in the current version and if not will it be possible in .NET 4?

  • Is there support for enums & lookup tables ?

  • Hi Julie,

    Thx and good to hear from you.  

    -somasegar

  • @ Aaron: Enums unfortunately did not make the EF4 release but is something at the top of our list for vNext.  Alex has a nice blog post on how to workaround the limitation here:  http://blogs.msdn.com/alexj/archive/2009/06/05/tip-23-how-to-fake-enums-in-ef-4.aspx.

  • @David

    If you need a DataTable, it is probably easiest to just use what is available in the SqlClient provider, specifically the SqlDataAdapter class. If you want to get a DataTable representation over an entity that you've modeled, you will need to write the code yourself to populate that table. One thing that might make this easier is to look at the ObjectStateEntry class and the CurrentValues property. This gives you a DbDataRecord view over the values of an entity, complete with the metadata you'd need to create the column types in your DataTable.

  • Thanx for the info Soma.

    Julie, we are waiting for the book to get into EF 4 :)

  • I tried the StoreGeneratedPattern="Identity" in EF4 but its presense doesn't allow you to omit a non-nullable field in your conceptual model.

    I think this is a big problem in EF. You shouldn't have to expose fields of your table that you don't wish to work with.

  • @Bill,

    You can certainly do what you want with the Entity Framework, but unfortunately there's not an easy way to set it up using the designer--you need to edit the XML directly.  The information which the EF uses comes in three parts: the conceptual model (CSDL), the schema of the database (SSDL), and the mapping between them (MSL).  All three of these parts live in different sections of the EDMX file which you edit with the designer.

    If you reverse engineer a model from the database, then the designer will read all of the schema from the database and put it into the SSDL.  It will also create a conceptual model which corresponds to that and a mapping between the two.  When you edit things on the designer surface you are editting the conceptual model.  If you delete a property from one of your entities, you are just deleting it from the conceptual model, so when you try to build the overall solution you will get an error saying that your database schema (ssdl) has something in it which you haven't mapped.  If you go to the model browser pane in the designer and look at the store section, you can see your tables and the properties in them which will include the thing you have deleted from the conceptual model.

    To solve your problem, what you need to do is open your EDMX file in the XML editor rather than the designer and then search for and delete the properties you don't want from all three parts.  Then when you reopen in the designer you will see that the properties are gone from the conceptual model *AND* from the store portion in the model browser.

    At this point it should be possible to build and use your solution and have the EF just ignore those properties.  Of course you have effectively lied to the EF about the shape of your database which means it will assume those properties don't exist.  If you try to insert a new entity into your DB, then the EF won't include those properties, and if they are non-nullable then your database will likely return an error.  If, however, the properties have defaults or if you just do updates and not inserts, then things should work just fine.

    - Danny

  • @dsimmons

    Thanks for your comment.

    Yes, your absolutely right. What you suggest would be fine *if* you didn't have to worry about the deleted fields returning if you needed to update the model from the DB again in the future. If you do, of course the removed fields will come back.

    Does it seem like a poor idea to have an attribute on the SSDL fields that could be set saying not to use / refresh them when you do an update from the DB in the future?

    Or create an SSDL ignore collection for an entity or something along those lines.

    One other question I had if you have the time was what's the preferred practice for this scenario:

    I have an employee entity. On the web server I frequently need to deal w/ the full employee record so I model the whole thing. But I have a Silverlight client that I only need to send a collection of Employee IDs and Names to.

    Sending full Employee object to the SL client is a waste. The only way I can think to do it using EF is to query my employee entities and select an anonymous type that has just ID and Name. I was hoping I wouldn't have to create DTOs and could maybe leverage the generated classes EF makes for my entities. But in this case maybe that's not possible?

  • What about support for generating the database schema from the model? The current version only lets you go from the database to the model, but, not the other way around. Is that supported?

    You need to add support for the ability to store collections of primitives. You also need support for ordered lists. There should be a way to just have this binary serialized into a BLOB. This can be done in other ORMs like Hibernate. I use this and I think I'll be sticking with Hibernate until it's supported in EF.

Page 1 of 3 (32 items) 123