Entity Framework 4.0 – Part4: How to use your own POCO’s
These tutorials are built using Visual Studio 2010 RC and .NET 4.0. RC. This means that Entity Framework 4.0 is used. At the moment of writing this, VS2010 and .NET 4.0 are not yet released as RTM so information provided in this post could change in the future.
In the previous articles I mainly talked about things you could already do with eelier version of Entity Framework. EF4.0 has some better tooling, we saw this already with the complex types. With the new version of Entity Framework there is also out of the box support for POCO (Plain Old CLR Objects). This I personally like very much because I’m not such a big fan of generated classes. Previously you didn’t have much choice. You had to work with the object’s that EF generated for you. Did you have some specific logic in your property getters or setters? Then you had to find another solution. Remapping your objects to something else was one of them. You could not rely on these generated classes to contain custom business logic. If you rebuilt the edmx, your custom logic would be removed and the classes would be regenerated. There were however some clever tricks to get POCO support working before EF4.0. For instance have a look at: Persistence Ignorance (POCO) Adapter for Entity Framework.
In EF4.0 we have POCO support, so we can use our own business objects, domain objects. so let’s jump into the code and see how we work with that. I’ll use the same database as I used before.
- Create a new console application
- Add a new file to the project, choose ADO.NET Entity Data Model
- Here we see the same screen as we did before. Again we’ll create a model based on the database. This is not obliged. You could create the model yourself, but for this I would just let EF generate the classes for you. You will save yourself a lot of time.
- Now we should select our data source, I’ll choose the same database that I used before
- It’s time to select the tables we want to work with. I’m just going to use the Article for this.
- If everything is fine, you should end up with the following diagram
-So let’s summarize what happened:
- EF retrieved the information on the database
- Retrieved specific information on the table where you want to create entities for
- Based on these entities, EF created the CSDL, SSDL and MSL
- EF created the entities for you to access your data in the underlying table
- For these entities, EF generated some classes
- These generated classes are the objects that we want to replace with our own objects
- Let’s first stop the auto generation process. Select your .edmx file in the solution explorer and press F4 to open the properties window. There you should see the property “Custom Tool†with the value: EntityModelCodeGenerator. Go ahead and delete that value. Just make the field empty. If you rebuild now, you’ll see immediately that the generated code behind file will go away.
- OK let’s start by creating our POCO. One thing to remember is that this has to be EXACTLY the same as your entity. Do it wrong and you WILL get exceptions…I’ll go over this later
- First let’s create the Article class
public class Article { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public Double Price { get; set; } public int Stock { get; set; } }
- As you can see this matches to my entity shown in the previous image
- Now we need a way of connecting to the model. The bridge between your POCO and the edmx file containing the mapping schema etc is the ObjectContext class. This class uses the connection string in the App.Config file to connect to the edmx file and the underlying table. The connection string is one of the parameters we need to pass to the base constructor of the ObjectContext. In this ObjectContext implementation we’ll also define the entities. This is called an ObjectSet, that’s what we are adding to the ObjectContext. Let’s have a look at this now:
public class ArticleModel:ObjectContext { public IObjectSet<Article> Articles { get; set; } public ArticleModel() : base("name=DemoDBEntities","DemoDBEntities") { if (Articles == null) Articles = CreateObjectSet<Article>(); } }
- I don’t think much explanation is needed anymore. The first parameter that I pass to the base constructor of the ObjectContext class is the connection string, the second one is the name of the container. There are some different ways that you can do this..the Object Browser tells you how:
- OK we’re almost done! Now let’s test run what we just created
class Program { static void Main(string[] args) { var am = new ArticleModel(); foreach (var art in am.Articles) { Console.WriteLine(art.Name); } Console.ReadLine(); }
Exceptions
Now something short on exceptions because exception can occur while working with your own POCO’s.
- Make sure your object properties are the same as the properties in your EF entity. If you don’t have the same properties, then you’ll receive an InvalidOperationException saying something like: Mapping and metadata information could not be found for EntityType ‘EFPOCO1.Article’. I don’t like these kind of errors because they do not show which column is wrong. You have match every property and see which one is different.
- Make sure your App.Config can be read. If the ObjectContext can’t locate the App.Config or the name of the connection string is incorrect then you’ll receive an ArgumentException saying something like: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
OK as you can see it isn’t that hard to use your own POCO’s. I’m not saying EF generated classes are bad, it’s just that if you have some specific logic that you want to have in your objects, then you’re kind of stuck and need to be creative.
Anyway, hope this was informative.