Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

Using Entity Framework with ASMX Web Services and WCF Web Service:

If you use ASMX WebService to expose Entity objects from Entity Framework... then the ASMX Webservice does not  include object graphs, one work around is to use Facade pattern or to use WCF Service.

The other important aspect of using ASMX Web Services along with Entity Framework is that the ASMX Client is not aware of the existence of EF v1 since the client solely deals with C# objects (not EntityObjects or ObjectContext).
Since the client is not aware of the ObjectContext hence the client cannot participate in change tracking since the client only receives the Current Values and not the Original values when the service sends the the Entity objects to the client.

Thus there are 2 drawbacks to using EntityFramework with ASMX Web Service:
1. Object state is not maintained... so to overcome this limitation we need insert/update single entity at a time and retrieve the original values for the entity being updated on the server/service end before calling Save Changes.
2. ASMX does not maintain object graphs... i.e. Customer.Reservations or Customer.Reservations.Trip relationships are not maintained. Thus you need to send these relationships separately from service to client.

WCF Web Service overcomes the object graph limitation of ASMX Web Service, but we need to insure that we are populating all the non-null scalar properties of all the objects in the object graph before calling Update.
WCF Web service still cannot overcome the second limitation of tracking changes to entities at the client end.

Also note that the "Customer" class in the Client is very different from the "Customer" class in the Entity

Framework Model Entities. They are incompatible with each other hence we cannot cast one to the other. However the .NET Framework translates the client "Customer" Entity to the EFv1 Model "customer" Entity once the entity is serialized back on the ASMX server end.

If you need change tracking enabled on the client then we need to use WCF Data Services which is available with VS 2010. ==============================================================================
In WCF when adding an object that has relationships, the framework assumes that every object in the object graph needs to be added to store. for e.g. in a Customer.Reservations.Trip object graph, when a Customer Entity is added to the store, the EFv1 assumes that it needs to a add a Reservations collection and also Trips for each Reservation.

Thus if we need to use existing Trips for reservations then we need to insure that we null out the Trip object reference from Reservations and set the TripReference to the EntityKey of the desired Trip instead.
==============================================================================
Web applications and Web Service applications (like ASMX and WCF) are stateless hence we cannot leverage the ObjectContext to do change tracking on the objects returned to the client by the Web Server (since the objectContext gets disposed after each page is rendered on the client) .
The EntityDataSource and ObjectDataSource does enable you to get over this limitation, but you need to tap into the correct events of these datasources and then write code to attach the changes entities back to the ObjectContext during updates.
ObjectDatasource is bound to a single Entity since it needs to provide for the insert, update and delete methods for the entity it is responsible for. thus we cannot persist object graphs with ObjectDataSource. for e.g. you need a separate ObjectDatasource for Customer and Address Entities.

Thus the normal way to use EntityFramework with Web Applications (during updates) is to requery the database during updates to get the Original values (insuring that these entities are detached ,using the MergeOption.NoTracking during retrieval) then use ApplyPropertyChanges to the original entity (by passing the modified entity as a parameter to ApplyPropertyChanges) and then attaching this entity to the ObjectContext before calling SaveChanges).
Note that ApplyPropertyChanges will only update the scalar properties, so you need to update NavigationProperties manually (setting the EntityReference.EntityKey values for foreign keys)
==============================================================================
One of the recommended ways to use EntityFramework with WCF or ASMX Web services is to convert the Entities into DTO (Data Transfer Objects) objects before passing them to the client and reconverting them to EF Entities on its way back from the client and then attaching them to the Object Context (as explained above) before calling SaveChanges

==============================================================================

Understanding Relationships and Associations in EFv1

The Golden Rule of EF is that it does not load entities/relationships unless you ask it to explicitly do so.
However there is 1 exception to this rule. This exception happens when you attach/detach entities from the ObjectContext.

If you detach an Entity in a ObjectGraph from the ObjectContext, then the ObjectContext removes the ObjectStateEntry for this Entity and all the relationship Objects associated with this Entity. For e.g. in a Customer.Order.OrderDetails if the Customer Entity is detached from the ObjectContext then you cannot traverse to the Order and OrderDetails Entities (that still exist in the ObjectContext) from the Customer Entity(which does not exist in the Object Context)

Conversely, if you JOIN a entity that is not in the ObjectContext with a Entity that is in the ObjContext then the First Entity will automatically be added to the ObjContext since relationships for the 2 Entities need to exist in the ObjContext.
=========================================================
You cannot attach an EntityCollection to an entity through its navigation property for e.g. you cannot code myContact.Addresses = myAddressEntityCollection
==========================================================
Cascade Deletes in EDM:

The Designer does not support specifying cascase deletes for a Entity. To enable cascasde deletes on a Entity in EDM use the Association definition in CSDL for the Entity.
for e.g. SalesOrderDetail (SOD) has a Foreign Key relationship with SalesOrderHeader (SalesOrderHeader 1 : SalesOrderDetail *) if you specify a cascade Delete on SalesOrderHeader Entity then calling deleteObject on SalesOrderHeader (SOH) Entity will send delete commands for SOH record and all the SOD records that reference the SOH record.

==========================================================

As a good design practise, if you use Cascade Deletes insure that Cascade delete facet is used both in the EDM as well as in the database. Even though it is not absolutely mandatory to have Cascade deletes on both Database and EDM (since you can see that just the Cascade delete spec on the SOH Entity in EDM will insure that SOH record and all related SOD records will be deleted from the database ... even though you dont have cascade delete configured in the database in the SOD table)
==============================================================

Maintaining relationships in Code

When Setting a Navigation property of a Entity (for e.g. setting the Contact Navigation property of Address Entity) the following rules apply :

If both objects are detached, no relationship object will be created. You are simply setting a property the CLR way.
If both objects are attached, a relationship object will be created.
If only one of the objects is attached, the other will become attached and a relationship object will be created. If that detached object is new, when it is attached to the context its EntityState will be Added.

One important rule to remember regarding synchronizing the EntityReference.Value and EntityReference.EntityKey properties is that when attaching an Entity which has a EntityReference (e.g. Address Entity with ContactReference) the Value property will take precedence and if the Value and EntityKey are out of sync, the EntityKey will be updated to match the Value.

======================================================
If you call .Load() method on a detached Entity then the .Load() operation will throw an exception. There is one exception to this rule. If you load entities using MergeOption.NoTracking, you will be able to call .Load() on such entities since these Entities are accessible by the ObjectContext. So the bottomline is that we need Objectontext to be able to call .Load() method to do deffered loading on EntityReference or EntityCollection.

Another rule to remember is that you cannot call .Load() on entities that have a EntityState.Added State since the ObjectContext uses the EntityKey of the Primary (Parent) Entity when loading the related (Child) Entity (and not the EntityKey of the child (even if the EntityKey of the child is present before calling .Load())
======================================================

You can use ObjContext.Add() to add a entity to the ObjContext and set the EntityState of the new Entity to EntityState.Added. here no relationships are added/updated.
You can also use EntityCollection.Add() method to add an entity to another entity's related EntityCollection
for e.g. contact has a Addresses EntityCollection so to add a new address use contact.Addresses.Add(newAddress) to add a new address to the Addresses EntityCollection.

Note that if the entity does not already exist in the ObjectContext then calling contact.Addresses.Add(myAddress) will cause a new Address Entity to be added to the ObjContext with EntityState.Added and it will also add a RelationshipEntry (a relationship object) with EntityState.Added which connects the Contact (contact) with the new address newAddress.

Note that if the entity already exists in the Objectcontext (being part theOtherContact.Addresses Collection), then calling contact.Addresses.Add(existingAddress) will add 2 RelationshipEntry objects to the ObjectStateEntry Collection, one with EntityState.Deleted and the other with EntityState.Added. This implies that the existingAddress Entity is removed from the theOtherContact.Addresses Collection and Added to the contact.Addresses

Collection..effectively reassigning the address entity from the theOtherContact to "contact". This is called moving an existing entity to a new object graph.
======================================================

You usually use ObjectContext.Attach() and EntityCollection.Attach() methods usually when you need to reconstruct the ObjectGraph after deserializing the objects as received from a ASMX Web Service Client.
Attach is usually used to connect existing Entities in the ObjectContext. When EntityCollection.Attach() is called the EntityState of the RelationshipEntry (the relationship object) remains as EntityState.unchanged whereas when EntityCollection.Add() method is called the EntityState of the relationship object changes to EntityState.Added or EntityState.Deleted as the situation demands.

=========================================================

LINQ To Entities Tips:

Select Many does Inner Join by default.   for e.g.

   1: from c in Contact 
   2: from a in c.Address 
   3: select c 

... this will do a Inner Join between the Contacts and Addresses Table and return only those Contacts that have a Address.
========================================================
Group Joins Do LEFT Join by default. e.g.

   1: from a in Address join c in Contact ON a.Contact.ContactID == c.ContactID Into g 
   2: WHERE a.CountryRegion == "US" select g; 

This query will do a left join on the Contact table and return contacts that have a address in "US" region

The following query :

   1: from c in Contact 
   2: join a in Address.Where(a1 => a1.CountryRegion == "US") on c.ContactID  equals a.Contact.ContactID into addresses 
   3: select new {c, addresses} 

will do a left join on the Address table and return All Contacts. In these Contacts only those will have its Address EntityCollection Populated which have a Address in the "US" region, the other contacts will have 0 Addresses in the Address collection (even if addresses for those contacts exist in the database but are in a different region)

========================================================

Linq to Entities does not support DefaultIfEmpty().... instead use .Include("Address") Query Builder method to do a Left JOIN or use Group Joins if you need more control like Filtering on the Address EntityCollection of Contact Entity

===================================================================

Use CreateSourceQuery() on the EntityReference or EntityCollection if you need to add filters during deferred loading of Entities (Deferred loading in EFv1 happens when you call Load() method on the EntityReference or EntityCollection.

for e.g.

   1: var cust=context.Contacts.OfType<Customer>().First(); 
   2: var sq = cust.Reservations.CreateSourceQuery().Where(r => r.ReservationDate > new DateTime(2008,1,1)); 
   3: cust.Reservations.Attach(sq); 

This populates only those reservations that are older than Jan 1 2008. This is the only way (in EFv1) to Attach a Range of Entities to a EntityCollection using the Attach() method
==================================================================

If you need to get the Foreign Key value for a entity e.g. to get the ContactID value from a Address Entity use this :

   1: address.ContactReference.EntityKey.EntityKeyValues.Where(k=> k.Key == "ContactID")
Posted on Tuesday, April 13, 2010 2:56 PM | Back to top


Comments on this post: Entity Framework v1 … Brief Synopsis and Tips – Part 2

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rohit Gupta | Powered by: GeeksWithBlogs.net