Object Services & Using the APIs


Part of the Entity Framework FAQ.


9.   Object Services


9.1.   What is ObjectContext.Detach() method used for?


ObjectContext.Detach() -- will detach an object from the ObjectStateManager associated with an object context so that it can be attached to some other context or reclaimed by the garbage collector. For more information, see Detaching Objects (Entity Framework).


9.2.   Can the container name and the connection string name be different?


Unfortunately if you want to use the parameterless constructor on the strongly typed context, these two things are tied.  The container name and the connection string name have to be the same.  Of course your context object doesn't necessarily have to have the same name as your container, but you would have to use IPOCO or maybe codegen events to modify the way things are generated, and that doesn't really address what you are asking for anyway.


What you can do, though, is pass the connection string into the constructor of your context (either the strongly typed, generated context or the base class ObjectContext) yourself and then of course you could hard code it, determine it dynamically, get it out of the config file or whatever.


Pasted from <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2349979&SiteID=1>


9.3.   How can I create an ObjectContext using a store connection that has already been created?


Sometimes there are security or other reasons why you would want to create a store connection and have EntityClient and the ObjectContext use it rather than creating the connection based on the connection string.  This can be done, but you must build the metadata workspace, use it and the store connection to build an entity connection and then pass that to the ObjectContext.  Here’s a sample:


string connectionString = @"Data Source=jeffreed-dev6\sqlexpress;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True";


SqlConnection sqlConnection = new SqlConnection(connectionString);


MetadataWorkspace workspace = new MetadataWorkspace(new string[] { "res://*/" }, new Assembly[] { Assembly.GetExecutingAssembly() });


EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection);


NorthwindEntities context = new NorthwindEntities(entityConnection);


Based on forum question you can find here <http://forums.microsoft.com/Forums/ShowPost.aspx?PostID=3715593&SiteID=1&mode=1>


10.       Lazy Load and Eager Load


10.1.Does Entity Framework support lazy loading and deep loading and how is the performance for these features? 


EF definitely supports both lazy loading and deep loading, and we've done a LOT of work to optimize performance. When you create a query it will, by default, just use lazy loading.  You can, however, opt-in on a per-query basis for eager loading of one or more relationships.  The performance for these features really depends on your particular usage scenario.  In some cases it's more efficient to query for everything up front.  In other cases, doing all of that in one round trip either might bring down additional data that you don't need or might even be less efficient because of the large joins that are required.  Like all things performance, you need to profile your individual situation and tune to get the best possible performance. For more information, see Shaping Query Results (Entity Framework).


Pasted from <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=573966&SiteID=1>


10.2.Why doesn't the EF automatically load related entities when I reference a navigation property if it hasn't already been loaded (like Linq to SQL does)?


The entity framework attempts to make everything explicit, so even with lazy loading, you must explicitly call  the Load method on the relationship in order to load its related entities.  That way you know exactly when round trips are made to the database.  As systems grow larger and more complex, this kind of explicitness can do a lot to improve overall supportability of the system.


10.3.Is it possible to make the EF implicitly load related entities (even though 11.2 says it doesn’t do that by default)?


Yes.  This is possible, but it does require some work.  Check out this series of blog posts: http://blogs.msdn.com/jkowalski/archive/2008/05/12/transparent-lazy-loading-for-entity-framework-part-1.aspx


11.       Serialization and Web Services


11.1.Is Entity Key serializable?


Yes Entity Key is serializable.  There were bugs around this in beta 2, but they have been fixed for beta 3.  Not only is the key serializable, but also if you serialize one of the generated entity classes its key will be serialized with it, and if you serialize an EntityReference which has associated relationship info the EntityKey of the related entity will be serialized along with it.


11.2.Is it possible to serialize a graph of related entities?  Why am I only getting one entity at a time when I do XML serialization?


The entity framework will, by default, generate classes which are binary serializable, and if you are using binary serialization, an entire graph of related entities will serialize at once.  This is the default behavior, for instance, if you add an entity to asp.net viewstate.  Similarly, as of SP1 beta, DataContract serialization will by default include entire graphs of entities (thanks to some changes in both the EF and WCF).  If you want to use XML serialization, though, the EF will only “shallowly” serialize meaning that you will get a single entity and not the graph of related entities. For more information, see Serializing Objects (Entity Framework).


11.3.Is it possible to serialize the ObjectContext?


In a word, no.  Beyond that, I’m not sure that I recommend trying.  See this blog post for some of the problems in this space in general, and this blog post for some data about strategies for web services.  If you are really persistent, you might want to check out the EntityBag project at http://code.msdn.microsoft.com/entitybag/, but as of this writing it has not been updated to work with SP1 beta (it works with beta 3).  Keep in mind, though, that EntityBag is a sample/experiment.  The EF team is working on a better out-of-the-box solution for v2.


11.4.How do I serialize derived entity types over a WCF service with DataContract serialization?


This did not work out of the box in beta 3, but as of SP1 beta it should work automatically.


11.5.What about ADO.Net Data Services (aka Astoria)?


ADO.Net Data Services can facilitate automatic creation of a REST oriented web service which easily exposes data from your EF model in a form suitable for use in a variety of client scenarios.  Check out http://blogs.msdn.com/astoriateam/ and ADO.NET Data Services Framework Overview for more info.


11.6.Does ApplyPropertyChanges affect EntityReference properties?  How do I merge a modified graph of entities back with my ObjectContext?


There are many scenarios where it is interesting to load an ObjectContext with the original state of some entities and then update that context to match a set of changes to those entities where those changes were made elsewhere so that the context was not able to track the changes as they happened.  Web services and asp.net web pages are particularly common examples of these scenarios since the client often has access to the data sent from a mid-tier machine but does not have direct access to the database and so probably doesn’t have an ObjectContext and likely isn’t even running the Entity Framework at all.  In these cases, the ApplyPropertyChanges method on ObjectContext can be used to efficiently compare an entity already attached to the context with an entity that is not attached and to update the attached entity to match while tracking those updates as if the property setters had been called on each property.  ApplyPropertyChanges only operates on a single entity at a time, though, and it only applies changes to “regular” properties of the entity.  By regular we mean that it doesn’t apply to navigation properties, and it doesn’t apply to non-persisted properties added in a partial class. For more information, see How to: Apply Changes Made to a Detached Object (Entity Framework).


If you need to apply changes to an entire graph of objects, then you need to walk the graph yourself and call ApplyPropertyChanges on each modified entity.  If there are entities which are new or should be deleted, then you need to track that information in some other form than just a modified graph because just having the new graph simply doesn’t include enough information to determine the state of all the entities.  When a graph is attached, the ObjectContext will maintain that information, but when it is detached you need some other mechanism to track that info.  One solution that works for some applications is to use a single key property and interpret certain values which are not valid keys as meaning something about the state (maybe an ID of 0 means an entity is new and -1 means it should be deleted).  Another thing some folks do is to add an entity state property to their entities and maintain that property themselves when the entity is detached.  In either case, you can then walk a graph, look at that extra information and use it to call either ApplyPropertyChanges, AddObject or DeleteObject on the context.  The only other thing to remember is that AddObject will add the entire graph so new objects must be disconnected from an incoming graph before calling Add—they can then be connected to the graph already in the context.


Another approach is to use something like http://code.msdn.microsoft.com/entitybag/.  Future versions of the EF will include functionality to automate more of this process.


12.       Databinding


12.1.Does ObjectQuery<T> and EntityCollection<T> support DataBinding for WinForms / WPF?  Where has the "ToBindingList" method gone?


Both ObjectQuery<T> and EntityCollection<T> implement IListSource which makes databinding more automatic rather than requiring explicit calls to methods like ToBindingList(). In fact, since the automatic mechanism is so much better, ToBindingList was removed. For more information, see Binding Objects to Controls (Entity Framework).


12.2.What about ASP.NET?


As of SP1 beta the EF includes a new EntityDataSource control and corresponding designer experience in VS which greatly simplifies the creation of asp.net sites with EF databinding.  In addition, ASP.NET Dynamic Data further automates the process. For more information, see EntityDataSource Web Server Control Overview.


 

Skip to main content