Jul 302012
 

This is probably a bit of a late announcement, but Microsoft has elected to make the Entity Framework an Open Source project on CodePlex!  The first officially supported packages (from the open source project) are  rumoured to be integrated as of Entity Framework v6 (as the Entity Framework team are currently working on version 5).

The main reason for the move to open source, evidentially, is to allow the developer community to build more providers for the Entity Framework.  This would allow potentially any database (or database alternative) to be used with an Entity model.  Exciting!

If you want to check out the current status of the Entity Framework (both Database-first and Code-first) you can download the Entity Framework 5 Release Candidate via Visual Studio’s distributed Package Manager -  NuGet.  The latest version includes a number of improvements and additions including (FINALLY!) support for Enums.

I might consider writing a separate article on the installation and use of NuGet just in case there are folks out there who haven’t installed and used it yet.  If you are interested in an article on using NuGet please leave a comment here.

To find out more about what is coming in the next version of the Entity Framework v5 check out the following link.  Here’s what I gleaned from the overview:  Note that it doesn’t appear that v5 will contain support for “Navigation Properties” (Foreign Keys/Relationships) from Unique Constraints!!

What’s New in EF5?

EF 5 includes bug fixes to the 4.3.1 release and a number of new features. Most of the new features are only available in applications targeting .NET 4.5, see the Compatibility section for more details.

  • Enum support allows you to have enum properties in your entity classes. This new feature is available for Model, Database and Code First.
  • Table-Valued functions in your database can now be used with Database First.
  • Spatial data types can now be exposed in your model using the DbGeography and DbGeometry types. Spatial data is supported in Model, Database and Code First.
  • The Performance enhancements that we recently blogged about are included in EF 5.
  • Visual Studio 11 includes LocalDb database server rather than SQLEXPRESS. During installation, the EntityFramework NuGet package checks which database server is available. The NuGet package will then update the configuration file by setting the default database server that Code First uses when creating a connection by convention. If SQLEXPRESS is running, it will be used. If SQLEXPRESS is not available then LocalDb will be registered as the default instead. No changes are made to the configuration file if it already contains a setting for the default connection factory.

The following new features are also available in the Entity Model Designer in Visual Studio 11 Beta:

  • Multiple-diagrams per model allows you to have several diagrams that visualize subsections of your overall model.
  • Shapes on the design surface can now have coloring applied.
  • Batch import of stored procedures allows multiple stored procedures to be added to the model during model creation

References

Open Source Announcement
[ http://weblogs.asp.net/scottgu/archive/2012/07/19/entity-framework-and-open-source.aspx ]

Entity Framework on Codeplex
[ http://entityframework.codeplex.com/ ]

Announcement about Entity Framework 5 (RC) available via NuGet
[ http://blogs.msdn.com/b/adonet/archive/2012/05/15/ef5-release-candidate-available-on-nuget.aspx ]

Introduction to EF (Database-First)
[ http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-model-amp-database-first-walkthrough.aspx ]

NuGet Entity Framework Package
[ http://nuget.org/packages/EntityFramework/ ]

NuGet: How to use the Package Manager
[ http://docs.nuget.org/docs/start-here/using-the-package-manager-console ]

Installing NuGet
[ http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c ]

Mar 302011
 

Hi there.

Renamed in the .Net Framework 4.0 from “ADO.net Data Services” to the new – more snappy – “WCF Data Services”, today I’m going to take a closer look at what drives this latest version.  If you look at the release notes there are a number of additions (as well as obviously using the much better Entity Framework v4):

  • Data binding,

  • Counting entities in an entity set,

  • Server-driven paging,

  • Query projections,

  • Custom data service providers,

  • Streaming of binary resources.

To find out what else is new check out What’s New in WCF Data Services.  Also you might want to look at Getting Started with WCF Data Services http://msdn.microsoft.com/en-us/library/cc668810.aspx

To start, I am going to take a look at the server-driven paging since paging has typically been one of those areas of functionality where, if implemented poorly, can really degrade performance of a database or website.

What you’ll need:

  • Visual Studio 2010 Service Pack 1
  • SQL Server 2008 R2 [any edition] with Service Pack 1 – although this should in theory work fine with SQL Server 2005 and 2008.
  • AdventureWorks Sample Database

We’ll be using the old favourite AdventureWorks sample database so that we have some data preloaded.  You can obtain the latest version for SQL Server 2008 R2 from Codeplex at the following location: http://msftdbprodsamples.codeplex.com/releases/view/55926.  The installer does a great job of installing the samples for you, for this article we’re just going to use the OLTP demo database, so you can ignore the others for now.  See the screenshot below, which is how it should look after it is installed (via SSMS):

If you’re not too sure how to go about setting up an Entity Framework data source with AdventureWorks, check out this article from MSDN.com – though please note it is written for use with Visual Studio 2008, not Visual Studio 2010 Service Pack 1: http://blogs.msdn.com/b/adonet/archive/2008/06/18/tutorial-entity-data-source-control.aspx

image image

What we’re going to do is create a new Solution with an ASP.net Web Application.  Once it is created, add a Class Library to the solution and then add a new Entity Framework data model.  I’ve called mine ‘AdventureWorksModel’ as you can see in the screenshot.  Choose to generate it from a database, and select the AdventureWorks2008R2 database.

When I tried to generate the Model, I received the following error message: ‘Unable to generate the model because of the following exception: ‘The table ‘AdventureWorks2008R2.Production.Document’ was referenced by a relationship, but was not found.’

To work around it, I unselected all the tables in the ‘Production’ schema, and just added the remaining tables instead.  I’ll take a look at this error later to see if I can find out where the errant relationship is causing problems.

At any rate, you should now have a half decent model to play with:

image

..moving on.  In your ASP.net Web Application project, make sure you add a reference to the DataAccess class library.  Then, it’s time to create the data service:

  1. In Solution Explorer, right-click the name of your ASP.NET project, and then click Add New Item.

  2. In the Add New Item dialog box, select WCF Data Service.

  3. For the name of the service, type AdventureWorksDataServices.

image

Visual Studio will show you some generated code.  You’ll need to add the name of your Entity Framework Data Context in the definition of the WCF Data Service, like below:

public class AdventureWorksDataServices : DataService<AdventureWorksModelContainer>

In Part 2, we’ll be looking at how to configure the WCF Data Service and then how to use some of the new features. 

Part 2 will be coming soon.

Jan 292011
 

Recently I alluded to writing a series of posts on the Entity Framework Futures, now referred to as the “Microsoft ADO.NET Entity Framework Feature Community Technology Preview 5“ which could really, really use a cool codename.

Introduction

If you’ve been following along on the Windows Workflow Rules Engine series of posts (links at the bottom of this article), you’d know that we have a working model sample already underway.  It is my plan to reuse this solution to embrace learning about code first and the recent Entity Framework CTP5.  I’m going to reuse the objects in that small sample, and demonstrate how to do some initial plumbing to get you up and running.

Here’s a link to the original solution, in case you’d like to see a “before and after” view of the solutions.  What we’ll be doing in part 1 is to simply provide a data storage solution underneath the existing data objects.  You’ll find that we don’t need to do much to “bolt” the Entity Framework onto the object model and to use a context to persist data to a database – all created through code.

Preparing the Solution

The Data Access Assembly

The first thing I had to do was add another class library (“DataAccess”) to the solution, to contain the actual data context definition and to provide for any helper methods and anything else specific to data persistence.  To this new class, I added references to System.Data.Entity and a local reference (relative) to the EntityFramework.dll (which you need to copy from the CTP5 release).  We also need a project reference to the BusinessObjects class.

Next, I added a data context class which for this example is very straightforward:

namespace DataAccess
{
    public class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }       
    }
}

Unit Test Project

Next, I added a new unit test project (DataAccess.UnitTests) to the solution explicitly to test the data access functionality.  I added a reference to System.Data.Entity and also a reference to the EntityFramework.dll and also added a new App.Config file, which I’ll use to explicitly provide connection string information for the Data Context.  This project also has project references to BusinessObjects and to the DataAccess assembly, of course.

Business Objects Assembly

I like to try and keep the data objects themselves as separate and clean as possible, so the only change to the existing project is to add a reference to the System.ComponentModel.DataAnnotations assembly.  We need this so we can add Data Annotations to the classes for use with the Entity Framework.

image

The Solution Structure

Changing the Data Object(s)

Now that we have everything pretty much in the right location, we need to modify the Employee class a little bit.  Thankfully, this is a fairly easy task.  I did a little refactoring to create a one-to-many relationship between an Employee and his/her manager, as well as a reverse navigation relationship, Manager to Employees.  Referencing System.ComponentModel.DataAnnotations allows us to decorate the class with attributes which the Entity Framework will use to create the database schema.

Here is the new and improved Employee entity.  You can see the data annotations – there was a small catch with the navigation properties, modelled as self joins, there seems to be a bug in CTP5 so the only realistic option right now is to go with Code First’s default column.  I couldn’t guarantee the use of Manager/Employees, so instead it has to be tested with a unit test for now.

namespace BusinessObjects
{
    public class Employee
    {
        [Key]
        public int EmployeeNumber { get; set; }

        [StringLength(100)]
        public string FirstName { get; set; }
        [StringLength(100)]
        public string Surname { get; set; }
        [StringLength(100)]
        public string JobTitle { get; set; }

//Enums are not supported!!?
//h
ttp://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/9a5d5a64-4de8-4685-8896-c5e8f66fda65
        public StateEnum Location { get; set; }

        [Required]
        public DateTime DateHired { get; set; }       

// we’ve got a bug here with self-joins
//h
ttp://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/05198b97-f178-49ba-91da-7a2516a9ad8d
// for now, we have to accept the default column generated by code-first
        public virtual Employee Manager { get; set; }
        public virtual ICollection<Employee> Employees { get; set; }
    }
}

Some notes on entity support..

  • Self joins are still a bit of a mess
  • No support for enums!  Bitterly disappointing really.
  • the Fluent API can be used to add extra annotations at runtime

Unit Test Configuration

In our unit tests, we can add the following method to ensure that the database model is dropped and recreated anytime the schema changes.  You’ll need a more practical solution for any real product work, of course.

[ClassInitialize]
public static void TestInitialize(TestContext testContext)
{
   DbDatabase.SetInitializer<EmployeeContext>(new
                  DropCreateDatabaseIfModelChanges<EmployeeContext>());
}

Finally, I’ve added an app.config to the unit test project, and in it, I’ve added a connection string which uses the same name as the Data Context.  This allows us to specify the connection settings (the default is to use SQL Express).

<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
<connectionStrings>       
<!–
http://blogs.msdn.com/b/adonet/archive/2010/09/02/ef-feature-ctp4-dbcontext-and-databases.aspx
–>
<add 
name="EmployeeContext"
providerName="System.Data.SqlClient"
connectionString="Server=.;Database=Employee;Integrated Security=True" /> 
</connectionStrings>
</configuration>

Basically, every time the tests are run, the model will be dropped and recreated.  It’s also a good time to seed test data for the unit tests.

Putting it all together

So to test out Code First for the first time, I’ve mocked up a very simple test which is almost verbatim from the sample linked below.  Please note that this is for demonstration purposes only and does not constitute a valid unit test approach – I’m merely demonstrating how Code First works.

[TestMethod]
public void TestAddData()
{
    using (var db = new EmployeeContext())
    {
        // Add an employee
        var john = new Employee {  EmployeeNumber = 1,
                                   FirstName = "John",
                                   Surname = "Smith", 
                                   DateHired = DateTime.Now.AddYears(-1) };
        db.Employees.Add(john);
        int recordsAffected = db.SaveChanges();

        Trace.WriteLine(String.Format("Saved {0} entities to the database", 
                                      recordsAffected));
    }
}

That’s pretty easy.  If we execute the test and everything is configured correctly, we should get the database created, and the single row inserted:

image

If we add a second test, we can add another record and include a relationship to the first row added in our initial test:

[TestMethod]
public void TestAddRelationshipsData()
{
    using (var db = new EmployeeContext())
    {
        Employee john = db.Employees.Where(x => x.EmployeeNumber == 1).First();

        // Add an employee
        var gary = new Employee { EmployeeNumber = 2,
                                    FirstName = "Gary",
                                    Surname = "Smith",
                                    DateHired = DateTime.Now.AddYears(-1),
                                    Manager = john};
        db.Employees.Add(gary);
        int recordsAffected = db.SaveChanges();

        Trace.WriteLine(String.Format("John has {0} Employees", 
                                       john.Employees.Count));
    }
}

Notice that we reload the first employee and specify the relationship when constructing the second employee.  Easy stuff!

image

Obviously this is for demonstration purposes only!  You should always encapsulate your test data either loaded as a static set (and cleaned up), or use a transaction scope to prevent any permanent commits to the database – unit tests should never leave any test data persisted!

Conclusion

That’s pretty much the rundown for Part 1.  We’ve seen how we can bolt EF’s code first onto an existing (albeit shallow) model, and programmatically cause the schema to be created.  There’s so much more to do though, and (as I’m frequently finding out) there are a lot of roadblocks to overcome, but thus far it is promising!

We’ll continue with Part 2 next week, once I’ve had a chance to explore more advanced concepts – mostly to do with security, configuration and indexing and so forth.

If you are interested in the updated solution files, please leave a comment and I’ll happily post them to this article.

Further Reading

Entity Framework CTP 5
[ http://www.microsoft.com/downloads/en/details.aspx?FamilyID=35adb688-f8a7-4d28-86b1-b6235385389d ]

Code First Walkthrough
[ http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-code-first-walkthrough.aspx ]

More on configuring Data Context
[ http://blogs.msdn.com/b/adonet/archive/2010/09/02/ef-feature-ctp4-dbcontext-and-databases.aspx ]

The fluent API samples
[ http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx ]

Referenced Articles

[ Rules Engine Part 1 ]
[ Rules Engine Part 2 ]