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

.NET 4.0 training kit – February release

A bit late but some days ago they released the updated Visual Studio 2010 and .NET 4.0 training kit. Enjoy this new fine release! Follow the link below to download

Visual Studio 2010 and .NET Framework 4 Training Kit – February Release

COM interop improvements with C#4.0

I already did a blog post about this some time ago: Better Office COM interop thanks to named and optional parameters

Here I talked mainly on how named and optional parameters make life easier for Office developers. This focus was more on that. But actually there are a some other points that didn’t get enough attention. Here are some other great improvements specifically for COM interop.

  • No more meaningless ref parameters.
  • Better indexer support, property accessing. No specific get/set needed anymore.
  • No more need for casting, we can use dynamic binding thanks to the Dynamic class.

I have found a screencast by Sam Ng who explains all this in about 10min.


Link to the original post –> How Do I: COM Interop and Office in C# 4.0?

Better Office COM interop thanks to named and optional parameters

In my last screencast I showed you how to work with two new features in C#4.0 which are named and optional parameters. Now in this post I will show you another way how you can benefit from these new features.

Remember when you had to create these Microsoft Word document with the Office interop API and had to pass all these tedious by ref parameters. Things you absolutely didn’t care about! But anyway the Office COM Interop assemblies were expecting them. Thanks to named and optional parameters this will all go away!

So let’s first start with adding a reference to the Microsoft Office Word Interop assembly.

image

Following is the code we had to write before we could use named and optional parameters.

class Program
{
   static void Main(string[] args)
   {
       object missing = System.Reflection.Missing.Value;
       object visible = true;

       //Create instance of Word application
       Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
       //Make the Word application visible
       wordApp.Visible = true;
       //Create instance of Word document
       Word.Document wordDocument;

       //Add document to document collection of word instance
       wordDocument = wordApp.Documents.Add(ref missing, ref missing, ref missing,ref visible);
       //Type text in our Word document
       wordApp.Selection.TypeText("This is my dynamically created word document");

       Console.WriteLine("Done");
       Console.In.ReadLine();

   }
}

As you can see we had to define this missing object and pass it when we added our Word document to the documents collection of the Microsoft Word application instance. This doesn’t mean that much but hey we had to add it anyway to make it work. Now with optional parameters this isn’t needed anymore. We can just leave them out!

wordDocument = wordApp.Documents.Add(ref visible);

Will this do the trick then? Well not really because now you have removed 3 missing objects and are left with the visible Boolean. To make it really work, we have to define which parameter the visible object represents. This can be done with the named parameter feature. Now the method call will look like this:

wordDocument = wordApp.Documents.Add(Visible:ref visible);

Isn’t this so cool? But wait it gets even better. Another new feature of C# 4.0 is that we don’t need to explicitly pass parameters by reference anymore. So we can clean our code up some more. Finally we will end up with this piece of code, which is by the way much more readable.

class Program
{
   static void Main(string[] args)
   {
       //Create instance of Word application
       Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
       //Make the Word application visible
       wordApp.Visible = true;
       //Create instance of Word document
       Word.Document wordDocument;

       //Add document to document collection of word instance
       wordDocument = wordApp.Documents.Add(Visible:true);
       //Type text in our Word document
       wordApp.Selection.TypeText("This is my dynamically created word document");

       Console.WriteLine("Done");
       Console.In.ReadLine();

   }
}

Screencast: .net 4.0 Named and Optional parameters

Since I installed Visual Studio 2010 Beta 2, I’m no investigating all the new features of .NET 4.0. I did a short video on the new named and optional parameters. The quality of the video is not fantastic, sorry for that. If you got any tips on proper encoding and better places where I can host the videos. Please let me know.

Hopefully you’ll like it.

Getting started with Visual Studio 2010 and TFS2010

A new year is just around the corner and it’s also time to start working with Visual Studio 2010, Team Foundation Server 2010 and .NET4.0. It’s packed full with new and cool features. Maybe I’ll even do some posts on these new features.

But how can you get started? Well that’s not too difficult. Microsoft has given us a lot of new VPC images for Christmas. Check out the list

Visual Studio 2010 Beta 2 and TFS2010 (Hyper-V)

Visual Studio 2010 Beta 2 and TFS2010 (Windows [7] Virtual PC)

Visual Studio 2010 Beta 2 and TFS2010 (Virtual PC 2007 SP1)

Want to start setting up an image yourself and just want to have the ISOs of Visual Studio 2010 Beta 2 and Team Foundatsion Server 2010 Beta 2? No problem, Microsoft also released these bits on the Microsoft Download site:

Microsoft Visual Studio 2010 Premium Beta 2

Microsoft Visual Studio 2010 Professional Beta 2

Microsoft Visual Studio 2010 Ultimate Beta 2

Microsoft Visual Studio Team Foundation Server 2010 Beta 2 (Some help is also provided: Team Foundation Installation Guide 2010)

Once everything is set up and installed, you probably want to start immediately trying out this new IDE, right? Check out this cool training kit full of demo’s, videos, hands on labs Visual Studio 2010 and .NET Framework 4 Training Kit

New Version of Visual Studio announced, Hello Visual Studio 2010, Hello .NET 4.0

And I can only say that I’m really looking forward to these new releases. I’ll try to give a summary of the video in this post. Like Norman Guagagno is saying VSTS 2010 will focus a lot more on ALM (Application Lifecycle Management), Architecture, Testing and several more things. With better ALM they want to involve all the different participants more in the same process and don’t integrate all the different work into a single process. What does this really mean? There are many different functions in an application lifecycle. For instance you have the analyst, the architect, the developer, the tester etc. The way it works now is that the analyst does the analysis, the architect does his logical design, the developer does his developing and the tester does his testing. Most of the time they do this in their own environment. This can sometimes lead to problems. They developer doesn’t entirely understand the logical design , the developer cannot reproduce a certain bug tester has gotten. With VSTS2010 they want all this to happen in the same environment. This will solve a lot of problems I think. Microsoft is also putting a lot of effort into creating the necessary tools ad features to make this all possible. In example there will be a lot of new tools for the architect. Microsoft has embraced UML so there will a tool for creating UML diagrams. There will also be a tool for creating better models, logical models that can even have constraints (f.e. you cannot link a presentation layer model directly to a database layer model). Another thing that I really like is the hysterical debugging. Like I said earlier sometimes a developer cannot reproduce a certain bug. Now if a tester and a developer would have access to the same environment or tool they would have some common ground. And this way it is possible to abstract environment data and share this through that same environment. This way the developer could get that abstracted data and entirely recreate the situation the tester was in.

There will also be several improvements to the already existing TFS(Team Foundation Server). There will be a better way to control the source, the work items, better dashboards to control what is in the TFS etc…

I know I didn’t talk a lot about .NET4.0 but this was a post purely on the new tool to use the new framework. The framework will be covered later.

If you want more details be sure to check out the following videos’s!


Norman Guadagno: Announcing Visual Studio Team System 2010

Architecture Day (Tuesday, September 30th):
- Cameron Skinner: Visual Studio Team System 2010 – Architecture
- “Top-down” design with Visual Studio Team System 2010
- “Bottom-up” Design with Visual Studio Team System 2010 Architect
- ARCast.TV – Peter Provost on what’s coming for Architects in Visual Studio Team System
Business Alignment (Wednesday, October 1st):
- Achieving Business Alignment with Visual Studio Team System 2010
- Agile Planning Templates in Visual Studio Team System 2010
- Enterprise Project Management with Visual Studio Team System 2010
- Requirements Management and Traceability with Visual Studio Team System 2010
Software Quality (Thursday, October 2nd):
- Better Software Quality with Visual Studio Team System 2010
- Manual Testing with Visual Studio Team System 2010
- Historical Debugger and Test Impact Analysis in Visual Studio Team System 2010
Team Foundation Server (Friday, October 3rd):
- Brian Harry: Team Foundation Server 2010
- Branching and Merging Visualization with Team Foundation Server 2010
- Enterprise Team Foundation Server Management with Mario Rodriguez
- Team Foundation Server 2010 Setup and Administration
- An early look at Team Foundation Build 2010 with Jim Lamb
- A first look at Visual Studio Team System Web Access 2010
- Update on Team Foundation Server Migration and Synchronization