Partager via


Sneak Preview: N-Tier development with Entity Framework 4.0

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.


 

Building applications that work across tiers is a core part of many application architectures. In .NET Framework 3.5 SP1 we provided basic functionality that enabled developers to serialize and de-serialize entities. However, the experience in the first version had limitations which required developers to do a non-trivial amount of work. As Alex very aptly puts it in his blog post, N-Tier development is not about transferring state between client and server. Indeed, that is the easy part! What you actually need is to:

  1. Infer what the state changes are that need to be applied from a disconnected graph.
  2. Communicate those changes to the persistence layer.

The API in the first version was designed to track changes on an object graph made of entities that notify state changes on them and then commit those changes to the database. However, once multiple changes have happened outside the reach of the state manager (i.e. on a different tier), it becomes very difficult to reflect them back in the state manager.

To address this problem, in .NET 4.0 we first added new lower level APIs that can be used to tell the state manager directly what changes need to be applied. The most representative methods in the new API are:

  • ObjectContext.ApplyOriginalValues
  • ObjectStateManager.ChangeObjectState
  • ObjectStateManager.ChangeRelationshipsState

Those APIs could be easily put to use, for instance, by customers that create their own Data Transfer Objects to do N-Tier development.

When we described these API’s on the EF Design blog, your feedback was that we needed to provide developers more of an end-to-end N-Tier experience on top of Entity Framework. Therefore we went back to work on figuring out how to not only enable the myriad of possible N-Tier approaches on top of the new API, but also which approaches we could actually implement and own.

One of these approaches, that seem to provide the most benefits, is to create entity classes that store just enough information about state changes within themselves. We discussed this approach of Self-Tracking Entities here. We are shipping a T4 template (not included in Beta 1 but will be available shortly after that; stay tuned for details) that can generate a set of classes and a set of extension methods for ObjectContext.

Here is a sneak peek of what is possible with self tracking entities:

 // Service-side code
public 

Order

  GetOrder(int orderID)
{
    using(var context = new 

OrderEntities

 ())
    {
        return context.Orders.Include("Lines")
            .Where(it => it.OrderID == orderID)
            .FirstOrDefault();
    }
}

public void ApplyChangesToOrders(

Order

  order)
{
    using(var context = new 

OrderEntities

 ())
    {
        context.Orders.ApplyChanges(order);
        ValidateChanges(context);
        context.SaveChanges();
    }
}

// Client-side code
public void ApplyDiscountOnClient(int orderID, decimal percentage)
{
    using(var client = new 

OrdersServiceClient

 ())
    {
        

Order

  order = client.GetOrder(orderID);
        foreach(var line in order.Lines)
        {
            line.PercentageDiscounted = percentage;
        }
        client.ApplyChangesToOrders(order);
    }
}

Notice that in this code, the ApplyChanges extension method will extract change information from the graph of self tracking entities that was modified on the client, and using the low level N-Tier API will reflect those changes in the ObjectStateManager so that they can be later saved to the database.

Keep monitoring the ADO.NET Team blog as we’ll be posting more in depth blogs on N-Tier and Self-Tracking Entities.

Thanks,

Diego Vega
Program Manager ADO.NET Entity Framework

Comments

  • Anonymous
    May 14, 2009
    PingBack from http://microsoft-sharepoint.simplynetdev.com/sneak-preview-n-tier-development-with-entity-framework-40/

  • Anonymous
    May 14, 2009
    Thank you for submitting this cool story - Trackback from DotNetShoutout

  • Anonymous
    May 14, 2009
    Not sure if this is the right place to ask. Will we have access to the changeset. It would be nice to be able to send just the changes over the wire. Also it would be nice to be able to construct a changeset from a dto changeset.

  • Anonymous
    May 14, 2009
    Thank you for submitting this cool story - Trackback from progg.ru

  • Anonymous
    May 14, 2009
    is this works with POCO object ?

  • Anonymous
    May 14, 2009
    "is this works with POCO object ?" => I have the same question

  • Anonymous
    May 14, 2009
    These self-tracking entities thing looks good for what it is. Regarding the broader topic of n-tier development with Entity Framework, one of the concerns I have about the n-tier story coming out of Microsoft these days is that there are so many different solutions. For example, RIA services, Astoria/data services, WCF, etc. As you develop your n-tier story, it would be helpful if you could clarify where it fits into these other projects.

  • Anonymous
    May 15, 2009
    @ Courtois, Jose Yes, the self-tracking entities will be POCOs in that they do not have any layering or metadata dependencies on the Entity Framework (i.e. no required EF interface, no required EF metadata, no required EF baseclasses). This is nice because you can use them with Silverlight. The self-tracking entities will have fields in them that store the changes. You can use the T4 template we'll provide to generate these POCO entities for you and it will include all of the code needed to fill in these fields...but you never see this code when you use your entity as it's all private in the entity. Jeff

  • Anonymous
    May 15, 2009
    @Peter Yes, the changeset will be public in that there is a general way to declare the state of each entity and the relationship changes. The extension method "ApplyChanges" is done in such a way that you can feed in changes that come from other sources, like Java or your own code that creates this changeset. With our T4 self tracking entity template, the changeset will be part of the DataContract of each entity, but there is no reason why it needs to be there if you have some other way of using this changeset. Jeff

  • Anonymous
    May 19, 2009
    Can you tell us where in Beta 1 these "low level APIs"are? I am assuming there is some support in the core .Net Framework assemblies (not System.Data.Entity) that can represent change tracking data.

  • Anonymous
    May 20, 2009
    @Peter The low level APIs that are described are on the ObjectContext class (ApplyOriginalValues), and on the ObjectStateManager (ChangeObjectState, ChangeRelationshipState). Currently there is nothing outside of System.Data.Entity in the .NET Framework assemblies that represents change tracking data. Most of this information can be stored in standard collections such as List<T>. There is no "State" enum in mscorlib or System.Core, if that is what you are asking. This area is likely going to see some evolution (from EF and others), and hopefully more pieces will make their way into the base framework. Jeff

  • Anonymous
    June 10, 2009
    Please note a problem that exists with EF v1 when applying changes to an entity that has a scalar property of binary type - EF always sets binary properties to modified state, even if the content of the binary arrays are the same between the original and updated entity. In our project we solved this change tracking by saving an additional crc for the binary property and re-calculating & comparing crc for the updated property. We choose this option instead of saving original value because binary data is large and passing a message that holds both original and updated binary data is too expensive.

  • Anonymous
    June 10, 2009
    &#160; Entity Framework 4.0 Beta 1(又称EF V2)与 .NET 4.0 Beta 1 一起发布,包含了一系列的重要改进:自定义代码生成、延迟加载、N层支持、POCO支持

  • Anonymous
    June 16, 2009
    Nice post, I am coming around to liking entity, I have been using it on MvcCms and once past the learning curve am becoming a real fan.  Keep up the great work! http://www.ranessoftwareconsulting.com/articles/8/map-my-fragments--why-i-like-entity-finally

  • Anonymous
    July 19, 2009
    is this works with POCO object ?

  • Anonymous
    October 03, 2009
    Nice article. Not often seen such a good work.

  • Anonymous
    November 25, 2009
    Hi I used the T4 template for creating self-tracking entities and tested with an example similar to the one you post here but when I made changes in the Client and post them back the changes are not saved in the DB because the State of the entity is kept as unchanged. I guess that I making something wrong here but WHAT? thanks, Ariel