Showing posts with label EntityFramework. Show all posts
Showing posts with label EntityFramework. Show all posts

Sunday, 18 December 2011

MVC3 EntityFramework POCO StructureMap

The purpose of this post is to explain how to setup an MVC3 solution which uses Entity Framework POCO as an Object-Relational Mapping (ORM) tool and StructureMap as an Inversion of Control (IoC) tool.

Step 1 - New MVC 3 Project

There are plenty of resources available to show you how to start a new MVC 3 Project in Visual Studio 2010 so i won't go into that...

Step 2 - Add Entity Framework 4.1 as your ORM

There are a few different ways to do this but i use the NuGet package which is pretty straight forward.

  1. Open your MVC3 project in VS2010
  2. Tools > Library Package Manager > Manage NuGet packages
    • Click 'Online' in the left hand menu so you can search for new packages
    • Search for 'Entity Framework' - at the time of writing, version 4.2 was available but you can also go direct to the nuget site and some previous versions may be available, for instance, i'm using version 4.1.10331.0
    • See http://nuget.org/packages/entityframework
  3. Simply click 'Install' button and the framework will be installed your machine for future use
  4. Now you have EF installed, right-click on the 'Models' folder (or where-ever you want your .edmx file to end up) in your solution and choose Add > New item
    • Under the 'Data' heading, choose 'ADO.Net Entity Data Model'
    • Follow the prompts accordingly...use Google for more info ;-)
Step 3 - Install and configure StructureMap

  1. You can get the latest version of StructureMap from here: http://sourceforge.net/projects/structuremap/ 
  2. The easiest way to install and configure Structure Map though, is to use the NuGet package manager again
  3. Similarly to step 2.2 above, search for 'structure' within the Online NuGet packages and you should find one (at the time of writing) called 'StructureMap.MVC3'
    • Be sure not to confuse this with another very similar package called 'StructureMap-MVC3' which is now deprecated
to be continued...

Friday, 28 October 2011

Understanding EF Add and Attach

The goal here is to understand when to use each method.

Particularly:

How do you update a single field of a table that has multiple non-nullable fields

Friday, 14 October 2011

Using Data Annotations and Validators with the Entity Framework

After a lot of searching around, i finally found the answer.

Because when you use an ORM like Entity Framework, your Model objects will often get clobbered whenever you change the Model in the Designer and it re-generates your classes for you.

As a result of this, you cannot apply any Data Annoation directly to the generated classes.

This post and this one by Scott Gu explains that the technique you need to employ is 'buddy classes'.

What i didn't understand is: what was the point of applying the MetadataType attribute to the generated class??? It would just get over-written as well!

What i think Scott fails to make clear is: you need to add a new, seperate, partial class and apply the MetadataType to that (the new class is 'partial to' the generated Entity class) - DO NOT apply the MetadataType to the generated class!

All that's mentioned is:

"...apply a “MetadataType” attribute to a partial class that is compiled with the tool-generated class"

Example speaks a thousand words:

Lets say we're using Database First approach (or Model first) and we have a Person entity which is generated automatically for us every time we update the *.EDMX file in the Visual Studio Data Model Designer.

So we need to add a new partial class called 'Person' to the solution (making sure it is in the same namespace as the generated 'Person' class)

Right click on the Project > Add > Class

Call it 'Person.cs'

Change the declaration of the class to have the 'partial' keyword.

Add another class to the same file (or a new physical file, doesn't matter) - lets call it Person_Metadata.

Then add the MetadataType attribute to the new partial Person class.

My Person.cs file now looks like:

namespace BusinessDomain
{
    [MetadataType(typeof(Person_Metadata))] 
    partial class Person
    {
        // You can put custom business logic in here too!
    }
    class Person_Metadata
    {
        [Required]
        public object Name
    }
}


VIOLIA! The Name property of the Person object now has the 'Required' attribute applied to it and this WILL NOT be over-written when you update your Model via the Designer.

NOTE: The return type of the 'Name' Property is 'object' because it allows you to change the Type of the Property within the Model without having to update the Person_Metadata class eg if you wanted to change Nullable Boolean to Boolean, etc. You should retain this strategy for all properties you put in the Metadata class.

You can continue to add various Properties to the Person_Metadata class and assign them various Data Annotations.

Monday, 10 October 2011

EntityFramework with Oracle; Table Mapping: String > NCLOB

When building your Entities and Relationships using the 'Model First' approach, I found the wizard would automatically map a Scalar Property that you defined as a 'string' to an Oracle datatype of 'NCLOB'.

This was happening because I did not define a 'Max Length' Attribute for the Scalar Property.

To change this: Select the Scalar Property in the Data Model Designer and hit F4 (to view its Properties window) and give it a Max Length. I found that anything up to '2000' would result in the the Oracle Mapping Type being varchar2(X) where X is the Max Length you have defined.

EntityFramework 4 and Oracle Foreign Key Relationship Building

Using a Model First approach to build your Entities and their Relationships and in turn, Generation Database from the Model, can have its quirks.

Here is a few procedural tips to ensure smooth sailing:

Define all Entity but do not explicitly add a property which would constitute a Foreign Key - you need to leave that up to the 'Add Association...' wizard.

So if you have an Entities/Tables:

BLOG > POST

Where A Blog can have multiple Posts and a Post can have a single Blog, then create two tables:

BLOG
BlogID (int32)
Name (string)
IsActive (boolean)

POST
PostID
Content (string)

To create the relationships between the two tables, now right click on one of the tables and choose 'Add > Association...'

You then need to configure things accordingly. In above example:

End1: BLOG
Multiplicity: 1 (One)
Navigation Property: (Checked) "Posts"

End2: BLOG
Multiplicity:* (Many)
Navigation Property: (Checked) "Blog"

Make sure you check this option: "Add foreign key properties to the 'POST' Entity"

Make the text down the bottom reads as follows:


"BLOG can have * (Many) instances of POST. Use BLOG.POSTS to access the POST instances.

POST can have 1 (One) instance of BLOG. Use POST.BLOG to access the BLOG instance."
Annoying Naming

Now when you're finished, you may notice that your POST Entity in the Data Model designer, now has a new Property called "BLOGBlog_ID".

I personally find this quite annoying, so if you just rename that scalar property, everything else will be updated (that needs to be) and you can call it something more appropriate EG "Blog_ID"


Data Type and Table Mapping Quirks

Once you have created your relationships, ensure that you right-click on an Entity in the Data Model designer and choose 'Table Mapping'.

I found the wizard would automatically map a Scalar Property that you defined as a 'string' to an Oracle datatype of 'NCLOB'.

This was happening because I did not define a 'Max Length' Attribute for the Scalar Property.

To change this: Select the Scalar Property in the Data Model Designer and hit F4 (to view its Properties window) and give it a Max Length. I found that anything up to '2000' would result in the the Oracle Mapping Type being varchar2(X) where X is the Max Length you have defined.