Partilhar via


Tip 38 – How to use CodeOnly with Astoria

The normal way that you create an ADO.NET Data Services (aka Astoria) Service is by creating a class that derives from DataService<T>.

public class BloggingService : DataService<BloggingEntities>

And if you want to use Entity Framework under the hood the T you supply must derive from ObjectContext.

Now this works great most of the time, but not with CodeOnly, and here’s why.

Under the hood the DataService constructs an instance of the BloggingEntities, and gets the model from it, via its MetadataWorkspace.

The problem is if you’ve configured the model using Code-Only, the only way to construct the BloggingEntities is via the Code-Only ContextBuilder, which Astoria knows nothing about.

Hmm….

Thankfully there is a very simple workaround, you simply override CreateDataSource() on DataService<T> like this:

protected override BloggingService CreateDataSource()
{
//Code-Only code goes here:
var contextBuilder = GetConfiguredContextBuilder();
var connection = GetSqlConnection();
return contextBuilder.Create(connection);
}

As you can see this is pretty simple.

Fine Print

For performance reasons it is important to avoid the cost of re-configuring the ContextBuilder each time, so the GetConfiguredContextBuilder() method should create and configure the builder only once, and cache the builder for subsequent calls.

Caveats

This tip will only work on .NET 4.0 Beta 2 and above.

Code-Only only works on .NET 4.0 and is only available as a separate download. ADO.NET Data Services (aka Astoria) is *going* to ship as part of .NET 4.0, but isn’t in Beta1, so you can’t use CodeOnly with Astoria yet, you have to wait for Astoria to show up in .NET 4.0 in Beta2, and you will probably want to wait for another drop of Code-Only too.

Which simply means you will have a wait a little while before you can try this tip out.