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

image

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

image

- Now we should select our data source, I’ll choose the same database that I used before

image

- It’s time to select the tables we want to work with. I’m just going to use the Article for this.

image

- If everything is fine, you should end up with the following diagram

image

-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

image

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

image

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

image

- 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();
    }

image

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.

Shout it
kick it on DotNetKicks.com

Entity Framework 4.0 – Part3: Complex types

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.

A complex type is a set of properties that you group together. Sometimes your code becomes more clear when you group together properties. In this part I’ll show you how you can create complex types from the designer. Before EF4.0, you could also create these complex types. The only downside was that you had to do it manually in the conceptual model.

In the previous post I created a new entity called Person. As you can see below, this Person entity contains all the classic properties.

image

Now I want to group Street, PostalCode and City together in a new complex type, Address. Then I have all the address related properties together. Procedure is as follows:

  • Hold CTRL and select the properties in the model that you want to group together
  • Click on the right mouse button and in the context menu select “Refactor into New Complex Type”

image

Now you’ll see that the model browser comes up and adds a new Complex Type. Now let’s give a more meaningful name. If you open the complex type, you’ll see the properties that we previously selected.

image image

If you look at your model, you’ll see that a ComplexProperty has been added to the list. If you look at the properties, you will see that the type of this ComplexProperty is actual the Address complex type that we just created.

I’ll rename this to Address as well, it will make it more clear.

image image

Ok now let’s see how we can use this complex type:

image

kick it on DotNetKicks.com

Entity Framework 4.0 – Part2: Updating the Entity model from a database

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 Part1 we have created our model from a database. Now you have made some changes to the underlying database and want to update the model.  For example: you created a new table in the database and also want to create an entity for this. No worries, you don’t need to delete the model and regenerate it.

Right click in the diagram and choose “Update Model from Database…”

image

This will open the Update Wizard. This window will show all the tables in the underlying database that are not yet represented by entities in your model. Here you can select the tables where you want to generate entities for.

image

Entity Framework 4.0 – Part1: How to create a model from a database

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 this series of blog posts I’ll explain to you how to work with Microsoft’s ORM, Entity Framework. Version 4.0 is used during the tutorials. I didn’t really blog that much before on Entity Framework because I thought the concept and usage was not ready. Now with the new release EF, I feel much more comfortable evangelizing it. Following, I’ll explain to you how you can create an entity framework model based on an already existing database.

Let’s start by creating a new console application and add a new file to the project. When the “Add new item window” comes up, select ADO.NET Entity Data Model.

image

Now the wizard will start. This wizard will help you to build up your entity model. Here you have two options:

  1. Generate from database: Here the model will be generated based on an existing database with tables.
  2. Empty model: Before Entity Framework 4.0 this didn’t really do much. But now this has changed a lot! From here you can create your own model (using the designer) and even generate a database script (to create the database and tables). How you can start from an empty Entity Framework model will be discussed in an upcoming post.

image

So we chose to generate the model from the database. This means we have select our database and tables. The wizard now asks us to select the database.

I’m going to create a “New Connection…” because I haven’t used this database before.

image

This dialog window isn’t new. If you have worked before with databases in Visual Studio, you should already be familiar with this window. It just asks you to select a server name and a database on that server.

image

Once the database has been selected, the wizard will generate the Entity connection string. This is something like a regular database connection string. The only difference is that it contains more information on the Entity Framework model. Make sure that you check “Save entity connection string in App.Config”. This will save the connection string to an App.Config file.

image

Next we need to select the tables where we want to generate entities for. In my demo I’m only going to work with the Article table. Notice that you can also add database views or stored procedures to your entity model.
Make sure that you check the two checkboxes on this window.

Pluralisation is something new in EF4.0. If you check this box, EF4.0 will pluralize the name of you entity sets based on the Entity name. This will make querying a lot more readable in your code. Before when you had an entity that called Article, you entity set would also be called Article. Now when your entity is called Article, the entity set will be called Articles. The pluralisation mechanism in Visual Studio is actually quite smart! It doesn’t just add an ‘’s’ at the end of the entity name. For instance: Category will pluralize to Categories and Ox will even be pluralized to Oxen. How neat is that? For now the pluralisation only works correctly for the English language. No problem though, you can easily create you own pluralisation service where you can add your own words. Dan Rigsby has a nice blog post on this: Entity Framework 4.0: Pluralization

image 

Once the model is completely generated, you will see that Visual Studio has created an .edmx file (the entity model) together with its generated code behind class and an App.Config (where we stored the entity connection string).

image

If you click on the .edmx file, you will see a diagram of the model.

image

The WPF text editor in Visual Studio 2010 allows us to zoom the model in and out via the scroll wheel on the mouse. If you have a lot of entities in your model, you can easily get a good overview of the diagram. Under the scrollbar you have some different options to alter the view of the diagram.

From top to bottom

  • Zoom in on the diagram
  • Zoom the diagram to 100%
  • Zoom out on the diagram
  • Launch the thumbnail viewer: This allows you to better navigate over the complete diagram

image 

If you select an entity and click on the mapping details you will see how the table fields are mapped to the properties of the entity. If you want you can change details in the properties window. Information that was set on the table fields is also set on the entity properties. For example if you create a field in the table with a max length of 100 (varchar(100)) this will also be set in the entity property. This is not something that you will find back in the generated code behind class of the model. It’s actually stored in the conceptual model.

image

image 

Now let’s write some code to retrieve data from the database. As you can see, you only need to create a new instance of you entity model. Then you can retrieve your records by calling the entity set of you entity. See how easy this is?

class Program
    {
        static void Main(string[] args)
        {
            using (var dbentities = new DemoDBEntities())
            {
                foreach (var article in dbentities.Articles)
                {
                    Console.WriteLine(string.Format("Name: {0}",article.Name));
                    Console.WriteLine(string.Format("Description: {0}",article.Description));
                    Console.WriteLine(string.Format("Price: {0}",article.Price));
                    Console.WriteLine(string.Format("Stock: {0}",article.Stock));
                    Console.WriteLine();
                }
            }
            Console.ReadLine();
        }
    }

image

Hope this was informative!

If you have any questions or remarks, please let me know..

kick it on DotNetKicks.com