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.

 

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 ]

 

A little late, but better late than never – the Entity Framework CTP 5 was released last month before Christmas, and now that I’m back, I’ll be doing a series of posts on Code First and CTP 5.  This is mainly to test out the new Object Validation which currently only is supported by Code First architectures.

Before we get into the nitty gritty behind the most recent CTP, why don’t we stop and take a quick look at where things are with the latest release.  First off, you’ll need .Net Framework 4 and a copy of Visual Studio 2010.  Next, grab the CTP from MSDN located here.

Let’s take a look at what is new in the fifth community technical preview (CTP) – from the release notes:

What is new?

This is the list of new and improved features in CTP5:

DbContext API

  • Model-First and Database-First support:
    New T4 templates is included for using DbContext/DbSet

  • Validation of objects on SaveChanges:
    Validation is based on the use of Data Annotations and currently only supported in Code First

  • Change tracking API:
    Allows you to access information and operations applicable to objects that are tracked by a DbContext

    • Access to Original, Current & Store Values

    • Entity state (i.e. Added, Unchanged, Modified, Deleted)

    • Explicit Loading: API to load the contents of a navigation property from the database

  • Databinding:
    DbSet.Local exposes an ObservableCollection representing the local contents of the DbSet. This is particularly useful when performing databinding in WPF applications. The new ToBindingList extension method can be used to obtain a binding list for Windows Forms applications.

  • No-Tracking Queries:
    This can be achieved via the AsNoTracking extension method on IQueryable<T>.

  • DbContext Configuration:
    Allows the following options to be configured for a DbContext instance:

    • Lazy Loading

    • Validate On Save

    • Auto Detect Changes

  • Raw SQL Query/Command execution:
    Allows raw SQL queries and commands to be executed via the SqlQuery & SqlCommand methods on DbContext.Database. The results can optionally be materialized into object instances that are tracked by the DbContext via the SqlQuery method on DbSet.

  • Improved concurrency conflict resolution:
    We have added better exception messages that allow access to the affected object instance and the ability to resolve the conflict using current, original and database values

  • DbContext.ObjectContext has moved:
    Rather than being a protected member we have made the underlying ObjectContext available via an explicitly implemented interface, this allows external components to make use of the underlying context. Getting the context now looks like: ((IObjectContextAdapter)myContext).ObjectContext

  • Excluding EdmMetadata Table:
    If Code First is generating your database and you wish to exclude the EdmMetadata table, this is now done by removing a convention (note that you do no longer need to do this when mapping to an existing database).

  • Types renamed in System.Data.Entity.Database namespace:

CTP4 Name

CTP5 Name

Database

DbDatabase

RecreateDatabaseIfModelChanges

DropCreateDatabaseIfModelChanges

AlwaysRecreateDatabase

DropCreateDatabaseAlways

Code First

  • Better Code First to Existing Database Support:
    CTP5 removes the need to switch off Database Initializers when working with existing databases with Code First. If you map to an existing database that Code First did not create then it will just ‘trust you’

  • Support for additional Data Annotation attributes:
    The full list of supported attributes now encompasses:

    • KeyAttribute

    • StringLengthAttribute

    • MaxLengthAttribute

    • ConcurrencyCheckAttribute

    • RequiredAttribute

    • TimestampAttribute

    • ComplexTypeAttribute

    • ColumnAttribute (placed on a property to specify the column name, ordinal & data type)

    • TableAttribute (placed on a class to specify the table name and schema)

    • InversePropertyAttribute (placed on a navigation property to specify the property that represents the other end of a relationship)

    • ForeignKeyAttribute (placed on a navigation property to specify the property that represents the foreign key of the relationship)

    • DatabaseGeneratedAttribute (placed on a property to specify how the database generates a value for the property, i.e. Identity, Computed or None)

    • NotMappedAttribute: Placed on a property or class to exclude it from the database

  • Fluent API Improvements:

    • Simplified table and column mapping

    • Ability to ignore classes & properties

  • Pluggable Conventions:
    Based on the large amount of feedback requesting this feature we have included an early preview in CTP5. We still have some work to do on this feature but we wanted to give you the chance to provide feedback before we RTM. We’ll provide more details on this feature in the coming weeks.

Other changes

  • New Assembly Name:
    Our assembly name has changed to EntityFramework.dll

There are a bunch of exciting new changes here, most notably around DataContext and Object binding properties.  I’m going to put together a few samples using Code First over the next week or so to show you how these new changes come into play in a real world scenario.

Whilst some of this functionality is new or improved, you might notice a lot of naming changes – it is quite clear that there is a great deal of refactoring going on under the covers including renaming of the assembly file!  This would seem to indicate a number of naming changes which will create significant code changes when porting from EFv4 to EFv5 in the future.

I’ll try to keep an eye on the most widespread changes as EFv5 CTPs are evolving.  Please keep in mind that the CTP releases are not sacrosanct, and sometimes the refactoring is reversed in later releases, so don’t treat it as set in stone.. yet.

 

Introduction

Now if you are like me, you’ve probably had some interest in POCO (plain old CLR objects) objects for at least some time.  They are an invaluable tool in the distributed systems and service oriented architecture areas, but up until now they’ve been inaccessible for those designs.

In a nutshell, both LINQ to SQL and Entity Framework (v1) class entities did not support serialization for the purpose of stateless transport(such as web service communication).  This stems from the embedded context tracking attributes, and the design which stipulates a fairly poor experience for those daring enough to detach entities and “pass them around”.

Enter the ADO.net Entity Framework v2.. ahem, version 4 which shipped in the early part of this year.  Whilst the EFv4 doesn’t support POCO objects out of the box (you have to use an online template), it’s easy enough to accomplish with minimal effort.  Plus, they can used (almost) as seamlessly as non-POCO objects.

Before we get into the nitty gritty of this particularly long post, I will direct your attention to the following MSDN article which covers most of the steps for harmonious life with POCO objects and WCF services.  What the article does not cover is handling somewhat more complex object graphs.  In other words, the MSDN scenario is fine with fairly basic (and bland) objects, but it’s pretty nasty when you have objects containing, well, joins (collections, relationships, yada yada).

Now what follows, is based on a number of other articles floating around the Internet.  I’m not trying to take any credit for (the majority), I’m just collating the information into one handy to reach place.  I’m also going to supply sample code in case you have any trouble getting it all configured.  The parts which are my implementation alone, I’ll highlight.

The Data Model

First, let us take a quick look at the sample data model.  Nothing fancy, I’ll admit, but enough for our purposes:

DB-Schema

Which we will use with a WCF Service or two.  You can use the attached T-SQL script to create and populate a SQL Server database (and later generate your EDMX model from that schema).  Next, create a solution containing WCF services, and add a ADO.net Entity Framework (v4) model.  You can see from my sample below, the model is admittedly not very complex.  Notice the “self join” on the Category table.  This is not an uncommon scenario in designing parent/child relationships at the DB level.  It also has the (awesome) advantage of generating Parent/Child navigation properties (you may need to do some renaming if you generated the model from my sample schema).

The Object Model

image

Solutions and Settings

Once you have generated the model, right click anywhere on the blank model surface and select “Add Code Generation Item”.  This prompts you with a bulky dialog window – select “Online Templates” from the left hand side tree view.

Poco-1 Poco-2

Select ADO.NET C# POCO Entity Generator and click OK a few times as needed.  The template builds up the POCO entities and removes the EDMX/Designer based implementation which the EF designer would have originally generated.  This leaves you with a number of new files in your solution, which should look a lot like the following:

image

Web Services

Now that I’ve got your attention, lets have a think about how we’re going to expose these via WCF.  I’ve created two WCF Services, SystemLogService.svc and ProductService.svc. 
The interface definition of each is per below:

image image

Don’t worry about those attributes just yet!  I’ll explain a little about why they are necessary shortly.  If you have reviewed the original MSDN article you’ll recall:

“The POCO proxy type cannot be directly serialized or deserialized by the Windows Communication Foundation (WCF), because the DataContractSerializer serialization engine can only serialize and deserialize known types. The proxy type is not a known type. For more information, see the Serializing POCO Proxies section in the Working with POCO Entities topic. To serialize POCO proxies as POCO entities, use the ProxyDataContractResolver class to map proxy types to POCO types during serialization.”

Which means that the default (runtime) classes generated by LINQ/EF are incompatible with WCF because WCF requires classes defined at compile time. 

The Solution

As such, you need to both disable the use of Proxies, and also label your web service methods with the [ApplyDataContractResolver] attribute as seen above.  You can obtain the details about this attribute from the MSDN article or from my sample solution.  You only need to use it on the service side.  This is as simple as creating a new class and pasting the implementation from either source.  Then add the attribute to decorate your web service definition (on the interfaces).

image

Now, for the part not previously covered – we generally encounter a problem with passing entities which are a little more complicated than the example POCO objects encountered in the MSDN article.  Take our sample application.  The System Log entities define a basic relationship, and the products include a (fairly standard) self join, allowing product categories to have a hierarchy.

If we then create a standard console application, and add a web service reference, we can observe the class definition from the generated WSDL (below). 

image

If you’re unsure about how to view the WSDL code within Visual Studio, simply follow these steps:

  1. Right Click on the Service Reference
  2. Select “View in Object Browser”
  3. From here, expand the namespace of the reference, then right click on one of the interfaces
  4. Select “Go To Definition”

image image image

Now assuming you have done everything correctly, you should be able to consume the web services and the POCO objects in your console application:

image

 

Execution

If we execute the code, the first web service call returns fine, with no errors.  The second call however, which returns a collection is not as fortunate.
When we step over the following line of code, we receive an exception with the following message:

SystemLog[] logs = logClient.GetLogEntryByCategoryId(1);

“The underlying connection was closed: The connection was closed unexpectedly.”

 

image 

Looking deeper into the service side of affairs (debugging), we may discover that the exception being thrown is, in fact, the following:

There was an error while trying to serialize parameter http://tempuri.org/:GetLogEntryByCategoryIdResult. The InnerException message was ‘Object graph for type ‘Products.WcfServices.SystemLogCategory’ contains cycles and cannot be serialized if reference tracking is disabled.’.  Please see InnerException for more details.

After a fair amount of searching, I found a way to work around this little problem.  Implementing the suggested attribute [CyclicReferencesAware(true)] to methods involving collections appears to fix the problem.  After applying the attribute and updating the service reference (just to be sure!)  you will find the call succeeds, as per below:

image

 

But Wait.. There’s More..

Just when you thought it was safe to go back into the ocean..  What happens when we want to send things the other direction

Let’s look ahead to a web service method which takes one of our POCO objects, and tries to apply an update.
The logic I’ve used here detects a new entity, and also when an existing entity can not be located in the data store.

image

So nothing terribly complicated, correct?  If we implement something on the client side – something very simple, like the following:

image

When we try to execute this rather simple update scenario, we get the same kind of exception we’ve seen before:

image

 

I love it when a plan comes together..

So what is the solution?  Well, rather simple, if somewhat complex in the implementation. 
The outcome I found which works quite well is to emit the same attribute into the generated WSDL on the client side, when the reference is created.
This turned out to be a pretty straightforward idea, but a terribly intriguing problem to try to solve.

Without delving too much into details (please download and examine the sample solution) the basic premise was two fold:

  1. Define the required files in a common or shared assembly that both the service and the client project can consume.
  2. Build a class which implements several WSDL extensions: IWsdlImportExtension, IServiceContractGenerationExtension,IOperationContractGenerationExtension and IOperationBehavior

Basically, the class is triggered when the WSDL is being imported, and it adds the appropriate [CyclicReferencesAware(true)] attribute above the appropriate methods. 
To do this, you must modify the client’s App.Config to include the following configuration:

image

When the WSDL import is called, the referenced extension finds operations decorated with the CyclicReferencesAware attribute (the export decorates them with a documentation text).
When an operation decorated with the attribute is found, the importer adds (writes) a reference to itself to the operations’s behavours collection. 
As the WSDL is being generated, it’s a relatively easy step to output the required attribute.

Now, when if you update the service reference the appropriate attribute is applied to the generated WSDL code, as you can see from the screenshot below:

image

Side Notes

The only thing I didn’t figure out was how to add the required using directive to the generated code, however it is very easy to add the reference yourself – just compile the client project and you’ll get the appropriate errors. 

Double click on one, right click on the reference and you can easily add it to the code.  I realise it’s a bad practice to modify generated code, but I ran out of patience and figured this wasn’t a terrible oversight.  If you find a nice way to fix this, please get in touch.

Running the solution after updating the configuration (and referencing the shared assembly) and now the previous code runs just fine.  You can check the database to ensure the update occurred.

image

 

Summary and Disclaimer

Thus far, I haven’t had much time to test this any further.  I’ve implemented it on a number of web service clients without any problems. 
I’ve not tried any further complicated scenarios, but I’d really appreciate any feedback if people find further problems.

To wrap up, I’ve included the sample project and T-SQL to create a database.  This is not production code, so please use it as a demo. 
There’s no encryption, compression or other types of scenarios we might encounter in a complete system. 
It is supplied “As-IS” and no warranty is implied :)

As always, if you have any feedback please leave it here or get in touch.

Seriously though, I sincerely hope this might help out some folks who are as intrigued and equally baffled with WCF and the Entity Framework.

Bon Appétit.  /R

[ Download Sample Project and Schema ]

Additional Reading

http://blogs.msdn.com/adonet/archive/2009/12/22/poco-proxies-part-1.aspx
http://blogs.msdn.com/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx

MSDN Walkthrough on POCO Entities

http://msdn.microsoft.com/en-us/library/ee705457.aspx

The source for the cyclic check is courtesy of:

http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html

 

Hi Everyone,

Well, I said I’d do it, and I will be – I’ve spent several hours putting together a sample DB and solution which demonstrates how to support Entity Framework (v4) POCO objects serialized in and out of WCF Services.

In a word, it’s going to be a lengthy article – maybe even several articles – as there are many things to address.  I was stuck on the last part of the scenario – sending objects back to be updated, but in the last 30 minutes I remembered what had to be done.

The sample solution will contain a test DB schema, a WCF Service project, a test client project (a console application) and some additional projects (class libraries) as well as an Entity Framework (v4) EDMX model which has been converted into POCO objects using the POCO Template Generator which you can install via Visual Studio 2010.

So now that the project is working in an end-to-end scenario, all I have to do is write up notes, capture some screenshots and also make notes of potential pitfalls and errors.  This is tricky stuff, but it is quite possible to accomplish.  Stay tuned, as the first post will be coming out this week!  If you want to be prepared in advance, I strongly suggest you have a play at generating POCO objects for your existing Entity Framework (v4) model.

Here’s a quick sample of things to come..

DB-Schema EDMX

  • This is a screenshot from SQL Management Studio’s SQL Diagrams, showing the raw schema
  • Next we have the EDMX (Entity Framework Entity Model) in all its glory

Poco-1 Poco-2

  • A screenshot of how to access the Code Generation template options from the EDMX designer
  • Next, we have a screenshot of the Online Templates – note the ADO.Net C# POCO Entity Generator is the first item

/R

 

Just a quick word to point out that the most recent version of the ADO.NET Entity Framework Feature Community Technology Preview 4 was released recently (on the 13th of July) and is worth a look if you are using the Entity Framework in any meaningful fashion.

Check back soon, we’ll have some notes on the good, the bad and the mischievous features of this CTP.

http://www.microsoft.com/downloads/details.aspx?familyid=4E094902-AEFF-4EE2-A12D-5881D4B0DD3E&displaylang=en

You can also check out news from the team blog

http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4announcement.aspx

Some notes lifted from the official announcement:

Productivity Improvements

We recently posted here about a set of productivity improvements we have been working on to simplify the process of writing data access code with the Entity Framework. CTP4 includes the core API surface and functionality that is described in the post. We’d love to hear your feedback on this simplified experience, be sure to check out the walkthrough.

Code First

Updates and enhancements to Code First include:

  • Moved to the System.Data.Entity.ModelConfiguration namespace

  • Refactored ContextBuilder into ModelBuilder and DbModel
    ModelBuilder is a high level component that lets you tweak a model, ModelBuilder then produces an immutable DbModel that can be used to construct a context. In the future DbModel will become a fundamental component of the EF stack as we look at other ways to build models beyond ModelBuilder.

  • More Model Discovery Conventions
    We posted details about the complete set of conventions we plan to support
    here
    In CTP4 we have implemented the following conventions:

    • Primary Key

    • Relationship Inverse

    • Foreign Key

    • Pluralization of Table Names

  • Support for Data Annotations
    We posted details about all the Data Annotations we plan to support
    here
    The annotations supported in CTP4 are:

    • Key

    • StringLength

    • ConcurrencyCheck

    • Required

    • Timestamp

    • DataMember

    • RelatedTo

    • MaxLength

    • StoreGenerated

  • Parameterless overload of MapSingleType()
    This allows you to configure table names without having to explicitly map every property

  • Improved Relationship Configuration API
    We’ve made some changes to the Fluent API methods used to configure relationships to make the API more explicit and intuitive. These changes are covered in the
    Code First Walkthrough .

Road Map

We are still working through the best ship vehicle to deliver a go-live release for these features. Your feedback has had a big impact on the Code First feature so far and we want to be careful not to lock down the API too quickly. That said we are getting consistent asks for a go-live for Code First and we are working to get to an RTM in the earliest feasible ship vehicle.

 

Hi There!

It’s been a busy time, and I realise I’ve been a bit remiss in getting some
new posts up on the site.  In recent weeks, I’ve been considering migrating away
from the rather limited Windows Live platform and onto my own custom blog (or
Word press etc).  For one thing, it seems that someone’s been messing with the Live Services platform, because I’ve lost the statistics option, and I can’t post from Live Writer..grrrr.

No matter, I’ve got some posts coming, and here’s a brief summary:

  • Threading and C#: A nice wrapper to implement “handling” of the Framework’s
    System.Threading.ThreadPool
  • Solution structure design, keeping it simple but powerful
  • Generating ADO.Net Entity Framework v4 POCO Proxies and passing them around
    via WCF web services,
  • Thoughts on IT

So, stay tuned..

 

Well, it’s been a busy week.  Unfortunately it hasn’t left me with much time to write any meaningful blog entries – apologies.  Last Friday I managed to implement an end-to-end solution for object graph serialization with Entity Framework (v4) POCO objects to and from WCF Web Services (note: for .Net clients only at this stage). 

It is a fairly complicated thing to explain, so I’m only going to go into detail if there is sufficient interest in the solution.  There is sufficient material to be found on the Internet (see my previous post for links), but it’s certainly not all in one place and you would have to combine aspects of a different example – in the case of supporting serialization back from the WCF client (via a generated proxy).

The summary goes something like this:

  1. Create edmx model
  2. Generate POCO entities using the template support
  3. Split the entities into a separate assembly
  4. Consume the entities and context via a Web Service (WCF) facade
  5. Implement a custom attribute to handle EF Proxies
  6. Implement a custom attribute to handle cyclic references (for entities with a self-reference) – (if needed)
  7. Implement a custom attribute to be outputted in the client proxy stub – (if needed)
  8. Use the common assembly with the client and the WCF service

So – in short – if you are interested in a detailed entry (or series of entries) please leave a comment here, otherwise I may get to the subject later in the year when I have more time (and if there is interest).

In other news, I did some work with a WinForms client and TreeView control which was my first Windows Application for quite a while.  I’ve got to say, I’m really impressed how easy it is to use TreeView controls in .Net WinForms over MFC/C++.  Back in the old days, TreeView controls were a bit tricky to work with – .Net makes it almost too easy.

 

There’s going to be more to this in coming posts, but I thought I’d add all the articles I’ve been reading ahead of schedule.  The long and short of the story is this –

I’ve managed to implement round trip CRUD operations using POCO (Plain Old CLR Objects) using a WCF Service & Client in conjunction with the ADO Entity Framework v4 (and Visual Studio 2010 RC).

In doing so, I’ve implemented all the “fun stuff” (plumbing, configuration, attributes, etc) but I’m currently investigating the options for supporting non-lazy loading queries which return a partial object graph.  Part of the problem I’m facing is with the POCO Proxies (which are unknown types at runtime) though I hope to have a solution soon.

Enjoy the reading, or please be patient, and I’ll write a post going into more detail soon!

POCO Templates for Entity Framework v4 (applies to RC as well):

http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/

How to set up POCO Entities using the template:

http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx

ADO Team – Creating and Serializing POCO Proxies:

http://blogs.msdn.com/adonet/archive/2009/12/22/poco-proxies-part-1.aspx
http://blogs.msdn.com/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx

MSDN – Serializing POCO Proxies:

http://msdn.microsoft.com/en-us/library/ee705457%28VS.100%29.aspx

Exposing POCO Entities via WCF (forum):

http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/1c37447a-e303-4947-a3ee-d2e6592aac0a

Debugging/Trace tips and tricks:

If you find yourself with the dreaded “Object graph for type ‘X.Y.Z’ contains cycles and cannot be serialized if reference tracking is disabled error”
then check out this outstanding article:  http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html

 

4ell for a while today, I’ve been trying to find a way to execute a specific dynamic query with the Entity Framework v4 – a query which could be used on a variety of different tables. 

I have a series of tables which share a common column definition (lets call it “DateEnd”, of type DateTime).  Our example use case scenario is that we might want to query one of the several tables for the most recent value for this common column.

So normally what we would create is something akin to the following (where Table is set dynamically):

SELECT TOP(1) [DateEnd]
FROM [<table>]
ORDER BY [DateEnd] desc

Now, the main problem here is how can you execute such a query within the constraints of the Entity Framework?

If you’ve investigated the API you’ll find it isn’t necessarily obvious how we would proceed. 

The first problem is that the design ties it strongly to mapped entities (as opposed to scalar values), and secondly the syntax ties it heavily to explicitly typed (using EntityTypes) queries where you have to know the base type at compile time – i.e. the following LINQ query requires we specify the source table at compile time:

DateTime mostRecentDate = (from d in db.Statistics
                                           orderby d.DateEnd descending
                                           select d.DateEnd).Take(1).FirstOrDefault();

Luckily, I have a solution which will achieve the desired result! 

The answer is to make use of the data ObjectContext.CreateQuery<T>(..) method. 

With CreateQuery, we must specify the expected type (in our example, we use DateTime).  We can create our query as you would normally expect – here’s a sample:

Note that values in italics should be the name of your DataContext type.

using(ContextName db = new ContextName())
{
      string currentTable = “Statistics”;
      string query = String.Format(“select value c.DateEnd from {0} as c order by c.DateEnd desc”, currentTable);
      DateTime query = db.CreateQuery<DateTime>(query).FirstOrDefault();
}

Now, here’s the trick – the query has to be specifically formatted.  A straight T-SQL compatible query won’t work! 
Let’s examine the example query from above:

string query = String.Format(“select value top(1) c.DateEnd from {0} as c order by c.DateEnd desc”, currentTable);

The two values in bold, above, are needed.  We have to specify that we are returning a value (hence, the first highlighted word) and then we must use the qualified object name – not the table name.  In other words if you are pluralizing tables in your model, the table “Statistic” would be “Statistics” – and therefore you would need to use “Statistics”.  Also note that the column used uses an alias (c.).

Now if we profile (trace) our query you can see it successfully queries as we would expect:

image

So if you are getting something along the lines of this error message:

“[..] could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near simple identifier, line 1, column [..].”

It most likely means you aren’t correctly using an alias.  Make sure you are using a table alias and prefixing it where appropriate.

Now you can go query mad!  Just kidding, please use this wisely.  Unfortunately, this method makes it possible to execute unwieldy queries against the data store directly.  So please use it very sparingly, and only if Stored Procedures or Functions are not appropriate to your scenario.

Cheers…R

Aussie Wine Guy


© 2012 Rob Sanders: Sanders Technology Suffusion theme by Sayontan Sinha
WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera