Entity Framework Designer Gets Some Love in Visual Studio 2012
I have to admit, I’ve been quite enamored with using Code First to build domain models that Entity Framework can use. And I’ve not paid a lot of attention to EDMX models, which you can build using the Entity Framework Designer via either Database First or Model First models. (See my May 2011 column, “Demystifying Entity Framework Strategies: Model Creation Workflow” [msdn.microsoft.com/magazine/hh148150], to learn about the differences between Code First, Model First and Database First.)
But way back when, I lived in the designer. Ready for the “I’m so old” jokes? I’m so old I used Entity Framework when you had to work with raw XML because there was no designer. It’s true. This was during the early betas before the first release. So the designer that came in Visual Studio 2008 was a major blessing. Microsoft did a great job, even though it’s always easy to find ways it could be better … or complain about what’s not there. In Visual Studio 2010, we gained Model First support and some other nice features in the designer such as pluralization and foreign key support.
Now, Visual Studio 2012 brings an even more enhanced designer. There are two big changes but also a lot of minor tweaks that just make life easier and bring a smile to my face—hopefully to yours, too.
1, 2, 3, Color!
You may already have heard about one notable improvement—the ability to add color to entities in the designer. And it’s a pretty simple feature to use. You can select one or more entities and then, in the properties window, choose a color for those entities as shown in Figure 1. Color is great for tagging entities visually. When you open a model, it’s very easy to see that certain entities relate to one another within the model. Even in a small model such as the one in Figure 2, it’s clear how useful this can be.
Figure 1 Changing the Color of Entities
Figure 2 Easily Visualize Entity Groupings with Color
Organize with Diagrams
The debates rage on about how many entities are too many for a model. For my brain, more than about 20 or 30 entities in a single model are visually and physically unmanageable. I mean that it’s both visually hard to take in all of that information at once and, when I want to work on one or more entities in the designer, it can be cumbersome. I often resort to the designer’s Model Browser to help me locate an entity on the design surface. With huge models (hundreds and hundreds of entities—something I just won’t ever attempt), you might experience design-time and runtime performance issues. (See the Microsoft Data Developer Center topic, “Performance Considerations for Entity Framework 5,” at bit.ly/OZTiUL.) There are third-party EDMX designers that overcome this problem by taking a different approach to working with large models. My preference is to create small models for use throughout my apps, but that’s not always an option. Having the ability to manage many entities in a single model in the designer is important.
The new designer helps developers with this problem by providing an oft-requested feature—diagrams. With model diagrams, you can create different design-time views of what’s in the model. You might want to have one view that displays the entire model, such as the one in Figure 2, and then use additional diagrams to represent different ways of grouping the entities. The designer provides a number of approaches for creating diagrams, but be careful of functions that will move an entity rather than duplicate it.
For example, I may want a diagram that presents only the entities I’ll need when focusing on customer management at design time. That might be Customer and ShippingAddresses in this particular model. There are a few ways you can achieve this. One is by selecting those entities, right-clicking on them and choosing the Move to New Diagram option from the context menu. This will create a new diagram with only those two entities, as shown in Figure 3. But because I used the Move option, those two entities are removed from the main diagram. You have to be careful if you want to keep a single diagram of the overall model. I like that the diagram is not a reflection of the model schema in that you can see navigation properties (for example, Customer.Orders) even though in that particular diagram the Orders entity isn’t visible.
Figure 3 Diagram Created Using the Move to New Diagram Feature
You can also create and manage diagrams through the designer’s Model Browser, shown in Figure 4. From the Model Browser you can select the diagram to view, as well as add and delete diagrams. You can also drag entities from the model (for example, in the Entity Types section of the CompanyDatabaseModel) onto a diagram surface. So if I wanted Customer and ShippingAddress to remain on Diagram 1, I could create a new diagram from the Model Browser and then drag Customer and ShippingAddress onto the surface.
Figure 4 Manage Diagrams from the Model Browser
Additionally, you can copy and paste entities from one diagram to another and any relevant associations will come along as well.
Keep in mind that the diagrams are design-time views—they don’t define the model in its entirety. You can always see the complete model in the Model Browser. Therefore, the duplication of entities from one diagram to another has no effect on your model or your application. But they’re not read-only views. You can still design your model and entities in these diagrams and those changes will affect the underlying model. I also appreciate that with any entity in a diagram, you can right-click on that entity and choose the “Include Related” option to pull in all entities that are directly related.
Default Code Generation: POCOs and DbContext
Another change that made me smile when I first discovered it is that, by default, the wizard for creating a new Entity Data Model now uses the Entity Framework 5 DbContext T4 Template. Since the release of Entity Framework 4.1 (which included Code First and the DbContext API), the EF team has recommended that developers begin new projects with the DbContext and Plain Old CLR Object (POCO) classes instead of the .NET 4 ObjectContext and classes that inherit from EntityObject. But Visual Studio 2010 used a code-generation template that defaulted to ObjectContext and EntityObjects. It was up to developers to install the EntityFramework.dll NuGet package and switch their EDMX to use the DbContext template. This meant you had to be aware of the new guidance and act on it.
Now the designer defaults to using the EF 5.x DbContext Generator template, creating a DbContext class and POCOs that are so much easier to use in your apps than the earlier types. The wizard will also pull in the reference to EntityFramework.dll, which is installed onto your computer along with Visual Studio 2012, so you don’t even need an Internet connection.
You can easily revert to using ObjectContext. Check the Microsoft Data Developer Center topic, “Reverting Back to ObjectContext Code Generation,” at bit.ly/OFjcLa.
Define Enum Types
The Microsoft .NET Framework 4.5 brings enum support to Entity Framework. You can use enums with EDMX and Code First. With EDMX, you need to make the model aware of the enum types so Entity Framework knows how to transform them in order to map them to database types. The Entity Framework designer lets you do this pretty easily.
If you reverse-engineer a database into an EDMX model, the wizard will interpret database columns as .NET types. You’ll have to then define your enum types and fix up properties. Here’s a quick look at that process.
The Return entity in my model has a property named Reason that maps to an integer. I want to represent Reason as an enum rather than having an extra database table and entity, and I can make this change in the designer. Right-click on the designer background and under Add New, you’ll see Enum Type is a new item on the list. Select that to get the Enum Type wizard, where you can define the enum as I’ve done in Figure 5. Enum types aren’t visible on the designer surface, but you can always get to them (to view, edit or delete) in the Model Browser.
Figure 5 Defining an Enum Type
Now that the model is aware of this enum type, I can use it in my entities. I’ll go back to the Return entity and edit the Properties of the Reason property. The type was originally Int32. The new enum type shows up in the Type dropdown list, as shown in Figure 6, but you have to scroll down to the bottom to find it. Once you’ve selected that type, Entity Framework knows how to transform an enum to a database value whether you’re writing LINQ queries, retrieving data or updating data.
Figure 6 Selecting a New Enum Type
Here, for example, is a LINQ query that filters on the ReturnReason enum:
When the query is executed in the database, the Broken enum is transformed to its enum value, 3, as shown in this bit of TSQL:
You may have noticed the Set Flags attribute and Reference external type checkboxes in Figure 5. EF supports bit-wise enums, allowing you to combine enums when setting or querying data. Set Flags specifies that the enum will be bit-wise. Pawel Kadluczka from the EF team has a great blog post, “Using Existing Enum Types in Entity Framework 5” (bit.ly/QIUz6y), which provides a detailed explanation of the functionality of the Reference external type checkbox.
Be aware that, as of the time of this writing, WCF Data Services 5 does not recognize enum types. Read more about this problem on the WCF Data Services team blog at blogs.msdn.com/astoriateam.
Batch-Import Stored Procedures
Figure 7 shows another feature I remember asking about a long time ago, and I’m quite happy to see it in the Entity Data Model Wizard in Visual Studio 2012. The designer in Visual Studio 2010 lets you map stored procedures to complex types, but you have to do it one stored procedure at a time. That feature still exists, but now there’s a shortcut. When you’re creating a Database First model, you can have the wizard create the functions from the stored procedures all at once and the wizard will create the necessary complex types to which the functions will map.
Figure 7 Creating Function Imports from Stored Procedures
Figure 8 shows the new function imports and their related complex types in the model browser. I typically don’t like to use the default names the wizard creates. But it’s still faster to let it create these assets for me and then edit the names, than it is to create them myself one by one.
Figure 8 The New Function Imports
If you want to create function imports from some of the stored procedures but create entity mappings (that is, use InsertContact any time you add a new contact and call SaveChanges) from some others, I recommend you do this in two passes. In the first pass you’d select only the stored procedures that should be imported as functions and their relevant complex types. Then, using the Update Model from Database feature, you can select the procedures you want to use for mapping and ensure that the “Import selected stored procedures …” checkbox isn’t checked on this second pass.
TVF and Geography Support
EF5 supports mapping to table-valued functions (TVFs) and spatial data (such as SqlGeography and SqlGeometry), and the designer also supports these features. You can find out how to use the designer to leverage these mappings by reading the walk-throughs related to TVFs and spatial types at, respectively, bit.ly/QCppJJ and bit.ly/VdbEUP.
As with the enum support, note that WCF Data Services 5 does not provide support for the geography types that you can define in your EF5 model.
It’s the Little Things
There are a slew of smaller improvements to the Entity Framework Designer that add up to a big overall effect, making use of the designer a smoother experience.
Move Properties In the designer you can reorganize properties in an entity so they’re listed in the order you prefer. In earlier versions, the only way to accomplish this was by editing the XML directly.
Schema in Table Selection When you create a Database First model or update a model from the database, the tables, views and other database objects are now organized by schema name. If you’ve gone to the trouble of organizing your database objects by schema, you’ll benefit here by being able to locate objects more easily. And you can easily eliminate objects that aren’t part of your domain, such as the dbo schema tables in Figure 9.
Figure 9 Grouping Database Objects by Schema Name
Column Facet Changes Reflected in Model Update The Update Model from Database Wizard now picks up changes to the column facets—Scale, Precision, MaxLength, Nullable, Unicode and FixedLength—and applies them to the relevant properties in your model. This will be a welcome change for many developers. You’ll still have to fix broken mappings when you make changes to column types, though. MSDN has a full description of the effects in the document “Changes Made to an .edmx File by the Update Model Wizard” (bit.ly/PTOwKB). At the time of this writing, the section describing the Column changes does not yet include the new details about the facets.
Highlight Related Entities on Selection This is another little charmer that can help you visually comprehend your model: When you select an entity or association in the designer, the related entities are highlighted as well.
A Note About the Refactor Item on the Context Menu Prerelease versions of Visual Studio 2012 included a designer feature that would refactor dependent code if you renamed an entity or a property. The feature didn’t make it into the final release of Visual Studio 2012, but there are some artifacts in the designer that might be a little confusing. The context menu has a Refactor item with Rename in a sub-menu. If you choose Rename from the Refactor menu, a window will pop up indicating that no code will be changed. Because the refactoring won’t happen, that window will never list anything.
While this article has focused on new features specific to the Entity Framework Designer in Visual Studio 2012, there are other enhancements in EF5 you shouldn’t miss. Most notable is how the underlying performance has been improved, thanks to the new Auto-Compiled Queries. You can read about this on the team blog post, “Sneak Preview: Entity Framework 5.0 Performance Improvements” (bit.ly/PLWu5l). Whether you’re building your models using the Entity Framework Designer or leveraging Code First to design your models, there’s plenty to be excited about with EF5.
Julie Lerman is a Microsoft MVP, .NET mentor and consultant who lives in the hills of Vermont. You can find her presenting on data access and other Microsoft .NET topics at user groups and conferences around the world. She blogs at thedatafarm.com/blog and is the author of “Programming Entity Framework” (2010) as well as a Code First edition (2011) and a DbContext edition (2012), all from O’Reilly Media. Follow her on Twitter at twitter.com/julielerman.
Thanks to the following technical expert for reviewing this article: Lawrence Jones