Dan Rigsby – Coding Up Style

Developer.Speaker.Blogger

Archive for the 'Entity Framework' Category

Entity Framework 4.0: Scalar and Void Functions

Posted by Dan Rigsby on 20th May 2009

One feature that was sorely missing in the first version of Entity Framework was the automated ability to work with stored procedures that didn’t return back entities.  This could have been sprocs that returned void, a scalar value, or some other custom construct. 

Entity Framework v1

In Entity Framework v1 you could create a “Function Import” from these stored procedures types, but there would be no generated code that would give you access to them directly in the ObjectContext object.  You could only access them via pure Entity SQL.

To add a “Function Import” you would just add the sproc to your entity model as your normally would, then right-click on the “Function Imports” in the “Model Browser”, and select “Add Function Import…”.  This would bring up the following screen which would allow you to add your function.

5-20-2009 10-32-34 AM

If you selected that the function returned an Entity, then you would be able to access that entity in the ObjectContext. However, if you selected scalar or void, then you would have to manually write some kind of Entity SQL.  It would be nice if these “Function Imports” appeared as operations in the ObjectContext as well.

Entity Framework 4.0 Solution

Microsoft finally completed the story for “Function Imports” in Entity Framework 4.0. As you can see in the image below, the “Add Function Import” dialog is virtually the same except for the new option to return a complex type.

5-20-2009 5-42-25 PM

You can select the None and Scalar return types as you could before.  However, when the “Function Import” is created, some new code is injected into the Model code behind file that materializes the stored procedure into an operation on the ObjectContext itself:

public ObjectResult<Nullable<global::System.Int32>> GetProductCountByCategoryId(

    Nullable<global::System.Int32> categoryID)

{

 

    ObjectParameter categoryIDParameter;

    if (categoryID.HasValue)

    {

        categoryIDParameter = new ObjectParameter("CategoryID", categoryID);

    }

    else

    {

        categoryIDParameter = new ObjectParameter(

            "CategoryID", 

            typeof(global::System.Int32));

    }

    return base.ExecuteFunction<Nullable<global::System.Int32>>(

        "GetProductCountByCategoryId", 

        categoryIDParameter);

}

 

A couple of nice things about this are:

  1. No matter what we select as the return type, it wraps it as a Nullable type since a database value can always be null
  2. The results are wrapped in an ObjectResult which makes it consistent with all other queries.

And as we expect, we can directly access these operations in our code:

using (var context = new NorthwindEntities())

{

    ObjectResult<int?> result =

        context.GetProductCountByCategoryId(1);

    

    MessageBox.Show(

        result.FirstOrDefault().Value.ToString());

}

 

New “Execute” operations

If you look at the last line of the code generated by “Add Function Import”, you might notice is making a call to a new method called ExecuteFunction<T>.  This method isn’t marked public, but there are two new methods on ObjectContext that we can use to execute functions:

  1. int ExecuteStoreCommand

    This method seems to work like “ExecuteCommand” and returns in int representing the result

  2. T ExecuteStoreQuery<T>

    This appears to be more of a combination of “ExecuteScalar”, “ExecuteNonQuery”, and “ExecuteReader”.

These methods give us the ability to run any imported stored procedure in a variety of ways.  Most users, will want to just stick with the generated operations, but its always good to have options!

DotNetKicks Image

Posted in Entity Framework | 3 Comments »

New Screencast: Custom Sprocs in Entity Framework

Posted by Dan Rigsby on 20th May 2009

screencast1thumb-thumb I have a new 8 min 35sec training webcast up over using custom stored procedures in Entity Framework.  This video introduces how to use custom sprocs in your Entity Framework model for inserts, updates, deletes, and custom sprocs for searching.  The video briefly talks about how to work with void and scalar sprocs, but doesn’t get far into these as this is a feature that is getting more attention in the next version of Entity Framework.

The video is available through JupiterMedia and can be viewed at http://www.internet.com/video/. Just look for the "Developer Video" titled "Custom Sprocs in Entity Framework".

Direct links are:
http://www.internet.com/player/index.php?bcpid=1534611832&bclid=1433966034&bctid=22915014001

DotNetKicks Image

Posted in Entity Framework, Webcast | No Comments »

Entity Framework 4.0: Pluralization

Posted by Dan Rigsby on 19th May 2009

One of the new features in Entity Framework 4.0 (EF v2) is a service call “Pluralization”.  This service is used to convert names of objects form singular and/or plural forms.  For instance, if you have a table in the database that has a plural name such as “Customers”, then Entity Framework will automatically generate both object Name and Entity Set Name to “Customers” as well.  The result is that in your code, the name will look like this:
 
Customers c = new Customers();

Ideally, it would have been nice for EF to see that the table was a plural name and set the object Name to a singular form.

Now, you may be thinking that this is pretty trivial since you can manually change the generated name, but when when you have dozens or hundreds of tables this can be tedious at best.

To use the PluralizationService when generating an Entity Framework model, you just select the option"Pluralize or singularize generated object names”:

Pluralization

Or if you are using the EDMGen.exe tool, you can opt in using the /pluralize option.

Example

In the Northwind database, all the tables have plural names. (Note: It is typically recommended to name your tables in the singular form).

 Pluralization3

When this database is generated using the PluralizationService, the names are set correctly.

Pluralization1 Pluralization2 

Manually using the PluralizationService

The PluralizationService is in the System.Data.Entity.Design.dll under the System.Data.Entity.Design.PluralizationServices namespace.

Pluralization4

It is an abstract class and hence, can’t be directly instantiated.  However, there is a static CreateService method on the class to access instances of the service for various cultures.  At this time, the only culture implemented is “en-us”.

It would have been very nice if this were implemented at a more core level of .Net since this could potentially be useful for a lot more than just for Entity Framework design.  Here are some examples using the service:

// Create an instance of the service for

// a particular culture (only 'en-us' atm)

PluralizationService ps =

    PluralizationService.CreateService(

         CultureInfo.GetCultureInfo("en-us"));

 

// Convert strings to plural or singular

string pluralName = ps.Pluralize("Goose");

string singularName = ps.Singularize("Territories");

// Note: Correctly returns Geese and Territory

 

// Check if strings are plural or singular

bool isPluralName = ps.IsPlural("Sheep");

bool isSingularName = ps.IsSingular("Sheep");

// Note: Correctly sees both of these as true

Adding your own pluralization mapping

There is an interface using by the PluralizationService called ICustomPluralizationMapping that isn’t publicly exposed.  However, since it is implemented, you can cast the service to this interface and make use of the AddWord method to add your own mapping.Pluralization5

In this example, we add a new word called “Foo” with the plural version being “Foos”:

// Create an instance of the service for

// a particular culture (only 'en-us' atm)

PluralizationService ps =

    PluralizationService.CreateService(

        CultureInfo.GetCultureInfo("en-us"));

 

// Cast to the mapping interface

ICustomPluralizationMapping mapping =

    ps as ICustomPluralizationMapping;

 

// Add a new word mapping

mapping.AddWord("Foo", "Foos");

You could then use the service to generate the metadata or use it in some other context:
EntityModelSchemaGenerator generator =

    new EntityModelSchemaGenerator(

        entityContainer,

        ps);

 

var edm = generator.GenerateMetadata(); 

DotNetKicks Image

Posted in Entity Framework | 4 Comments »

New Webcast: ADO.Net Entity Framework

Posted by Dan Rigsby on 11th December 2008

screencast1I have a new 8 min 57 sec training webcast up over ADO.Net Entity Framework.  This is a primer video to help get you started using the technology.  It covers what Entity Framework is, how to get started using it, how to query the database, how to add items to a database, and highlights of couple of “features”.

The video is available through JupiterMedia and can be viewed at http://www.internet.com/video/. Just look for the “Developer Video” titled “ADO.Net Entity Framework”.

Direct links are:
http://www.internet.com/player/index.php?bcpid=1534611832&bclid=1433966034&bctid=4551661001
http://link.brightcove.com/services/link/bcpid1431564240/bclid1433966034/bctid4551661001

DotNetKicks Image

Posted in Entity Framework, Webcast | 1 Comment »