Entity Framework in .NET 4
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…’:
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:
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!
Anonymous
January 11, 2010
Is this available in VS10Beta2?Anonymous
January 11, 2010
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?Anonymous
January 12, 2010
@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!)Anonymous
January 12, 2010
The comment has been removedAnonymous
January 12, 2010
@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.Anonymous
January 12, 2010
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?Anonymous
January 12, 2010
Is there support for enums & lookup tables ?Anonymous
January 12, 2010
Hi Julie, Thx and good to hear from you. -somasegarAnonymous
January 12, 2010
@ 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.Anonymous
January 12, 2010
@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.Anonymous
January 12, 2010
Thanx for the info Soma. Julie, we are waiting for the book to get into EF 4 :)Anonymous
January 13, 2010
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.Anonymous
January 13, 2010
@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
Anonymous
January 13, 2010
@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?Anonymous
January 13, 2010
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.Anonymous
January 14, 2010
@Jon EF4 does support "Model 1st" so you can create the database from the model (although I think that's a poor approach that values the app over the data). I'm not sure I understand what you mean by primitive collections though (Sounds like an array !?) and ordered lists. Can you give an example of when you'd want to do that?Anonymous
January 14, 2010
Hi Soma, Recently I came up with some performance issue Dataview Filter. I was trying to filter the data in dataview using Rowfilter and was assigning to grid, worked fine but when the same thing I was implementing using Datatable.Select, the performance was much faster than expected. It almost saved my 26 sec (checked in both .NET performance tool and Jet Profiler). So whether the LINQ will be faster than that this or will be equivalent to Dataview.RowFilter. Please brief some idea on this. :) Regards Rishi DaftaryAnonymous
January 18, 2010
@Rishi Using LINQ to Dataset should result in better performance than DataTable.Select. Having said that, performance is something that depends on a lot of factors - number of rows, type of operations being performed etc, so there's no harm in trying both approaches and seeing what works better for your application. Hope that helps, JonathanAnonymous
January 18, 2010
Hi Jonathan, thnx for the reply. Anyways can you please explain why dataview.rowfilter takes more time than datatable.select. Difference is almost 26 sec which is really huge. So was just eager to know the internal details of how dataview.rowfilter works. nd thnx for the help... Regards RishiAnonymous
January 18, 2010
This is also an article on some of new features in asp.net 4 and visual studio 2010 IDE http://www.codeproject.com/KB/aspnet/Whatis_New_ASP_Net_4.aspxAnonymous
January 28, 2010
Soma, Could you please guide us on what is Microsoft's strategy going forward with Windows Mobile and how much Silverlight will be involved in that initiative. What tools will VS.NET 2010 provide to develop mobile applications? Secondly, why has Microsoft been shying away from introducing its "own" phone for such a long time now? Clearly the partner approach is not working in this domain. Thirdly, even after having .NET around for approx. 10 years now, why hasn't Microsoft provided an elegant and simple way to create Office documents? Excel or Word automation / using the dlls directly in projects have proven to be a pain and clearly a bad approach so far. Third party products are the only "real" options business developers have till date. This is clearly been a weakness in .NET framework and for whatever historic and business reasons the Office team wants to stick to COM its starting to look bad. It's time to move on... Office documents shoud be the easiest things to create with .NETAnonymous
January 31, 2010
Bill: Have you considered creating a View with the appropriate columns for silverlight and using that as the basis for your Silverlight data?Anonymous
February 01, 2010
Unfortunately, EF looks like it suffers the same problem as the old Enterprise Library - overly complex and too bloated for quick use. I find LINQ to SQL to be more than enough for daily needs.Anonymous
February 08, 2010
agreed but unfortunately L2S is deprecated for future work in favor of EF.Anonymous
June 14, 2010
The comment has been removedAnonymous
June 14, 2010
Your architecture team would leverage views or stored procedures as an interception layer for the data access layer. They could also choose to build a wrapping provider to intercept all interaction with the database: code.msdn.microsoft.com/EFProviderWrappers. -TimAnonymous
June 15, 2010
The comment has been removedAnonymous
June 15, 2010
The comment has been removedAnonymous
June 29, 2010
The new StoreGeneratedPattern attribute added in EF4 still doesn't work (it only update the CSDL). We have to keep updating the SSDL manually (with a risk to loose it when updating the model). I was really surprised that MSFT missed this point in EF v1. But now, I just can't believe, MSFT missed this point AGAIN in EF4 RTM !Anonymous
June 30, 2010
The comment has been removedAnonymous
August 04, 2011
Why was this not done in EF 3.5 - I am so sick and tired of Microsoft releasing things that are not feature complete thinking they are doing developer's a favor but in reality tying our hands. I have a common database that is used for applications of both versions that allow the apps to get common data (i.e. common corporate data) - the .NET 4.0 EF library is fine/dandy - but trying to create an EF 3.5 version is impossible because the foreign key properties are not visible in the EF 3.5 entity objects so the standard function imports will not work because the entity objects don't have FK property values which are used as filtering criteria to the function (SPROC).Anonymous
August 05, 2011
@EF .NET 35 You are correct that EF 3.5 was not a very successful release as it limited the number of data access patterns you could use practically. For some people it was just fine, but for others it made things very challenging. In the particular case you mentioned, you can still access the FK values via the EntityReference.EntityKey property or via the navigation property and use these to pass into your stored procedure, but it is a work-around. In .NET 3.5 the EF team didn’t focus enough on the complete ORM story. In EF 4.0 and EF 4.1, we did a lot more listening to how .NET customers wanted to use an ORM technology on our platform and how it could be used in solutions like WPF or MVC applications so I'm glad you found the 4.0 release to be better. In the next release of the EF, we hope to have even more ORM improvements such as enums and migrations (things we’ve mentioned on the ADO.NET team blog), so it’d be great for us to get your input on the previews we have available there. -Jeff