EDM -> POCO -> WCF (.NET4) But transferring Collections causes IsReadOnly set to TRUE - wcf

Ok, this may sound a little 'unorthodox', but...using VS2010 and the new POCO t4 template for Entity Framework (Walkthrough: POCO Template for the Entity Framework), I can generate nice POCO's. I can then use these POCO's (as DTO's) in a WCF service essentially going from EDM all the way through to the client. Kinda what this guys is doing (POCO with EF 4.0 and WCF 4.0), except everything is generated automatically. I understand that an entity and a DTO 'should' be different, but in this case, I'm handling client and server, and there's some real advantages to having the DTO in the model and automatically generated.
My problem is, that when I transfer an entity that has a relationship, the client generated collection (ICollection) has the read-only value set, so I can't manipulate that relationship. For example, retrieving an existing Order, I can't add a product to the Products collection client-side...the Products collection is read-only.
I would prefer to do a bunch of client side 'order-editing' and then send the updated order back rather than making dozens of server round trips (eg AddProductToOrder(product)). I'd also prefer not to have a bunch of thunking between Entity and DTO. So all-in-all this looks good to me...except for the read-only part.
Is there a solution, or is this too much against the SOA grain?

The FixupCollection which is assigned to your ICollection is recreated as an Array when the deserialization occurs. Th'at's why your Products collection is read-only.
In order to modify this, you can use the option (existing at least on VS2010) in the "Add Service Reference", to change the Collection type to something else (Generic.List or Generic.Observable).
But, if you use the option to reuse type existing in existing assembly and referencing the assembly containing your entity, the previous option will not be applied to existing type and you will still have Array in your Products collection.
A workaround i use (only if you reuse type on client side and reference your entity assembly) is to modify the T4 template to check if the collection is read-only in the get of Products, and set an FixupCollection if it does:
if (<#=code.FieldName(navProperty)#>.IsReadOnly)
{
var newCollection = new FixupCollection<<#=code.Escape(navProperty.ToEndMember.GetEntityType())#>>(<#=code.FieldName(navProperty)#>);
newCollection.CollectionChanged += Fixup<#=navProperty.Name#>;
<#=code.FieldName(navProperty)#> = newCollection;
}

"la mouette" solution works with referenced assemblies:
We have the same problem, and we have noticed that the property IsReadOnly is setted to true after wcf serialization (Before that, the property value is false).
We have referenced assemblies. In the workaround proposed by "la mouette", use a parametrized constructor, but our POCO template doesn't have one.
We have modified the tt creating an empty constructor to invoke the base one, and that do the trick.

Related

Why this EntityManagerSaveException?

I am using Silverlight 4 and DevForce 6.1.11.0
I have some POCO classes that implement EntityAspect.
When changes are saved via EntityManager.SaveChanges; DevForce does not save these POCO entities to the server, because these POCO entities are not part of EF.
Instead I send them to a webservice via WebClient.UploadStringAsync.
This works, expect when I am saving more than one entity of the same type. Then I get this exception:
EntityManagerSaveException: An entity with this key: PocoMyClass: 0,0
already exists in this entityManager
I have checked the cache, and there is no entity with that key.
The WebClient.UploadStringAsync still sends the data and everything gets saved, but the exception does not look good to customers.
How do I work around this exception?
The poco entities that I am having problems with are only supposed to live on the client, not the DevForce server. The reason is that only the client can access these on the local network.
So I am using WebClient.OpenReadAsync to read the data in and create the poco entities on the client. And then I use WebClient.UploadStringAsync when saving the poco entities.
When creating the poco entity and adding it to the entitymanager, I do like this:
var pocoEntity = new PocoMyClass();
pocoEntity.keyId = some integer;
…
entityManager.AddEntity(pocoEntity);
pocoEntity.EntityAspect.AcceptChanges();
After doing this I see that the properties for EntityVersion.Original of the poco entity only contains empty stuff (NULL´s and zero’s).
Is this the reason for the exception when saving?
How can I manipulate EntityVersion.Original when the entity does not come from the DevForce server?

Return Entity Framework objects from WCF

I am working on a WCF service to provide data to multiple mobile clients. Data model is Entity Framework 4.0. Schema is given below.
When i returnt he object of SysUser the result also contains the navigation properties and EntityKey and other EF related stuff. Is it possible that i get the pure object(only the database fields without the relationship etc).
Thanks
Update
the exception occures "Only parameterless constructors and initializers are supported in LINQ to Entities." on followign code:
return (from u in DataSource.SysUsers
where u.UserID == UserID
select new Player(u)
).FirstOrDefault();
You probably want to send DTOs across the wire rather than your EF objects.
You could use something like AutoMapper to populate your DTOs from the EF objects.
I think if you remove the virtual keyword in your SysUser model for the navigation properties, those will not be loaded. Later, if you need to load this properties, you can do it manually as stated here: http://msdn.microsoft.com/en-us/data/jj574232
Now, if you want to make SysUser travel through a WCF service, it is not a good idea. First, your service's client will need a reference to your Models Project... and that doesn't feels right. If you don't reference your Models, you will get a proxy for it, that is more or less the same as Joe R explained about DTOs.
Here is a related answer: https://stackoverflow.com/a/7161377/7720

Share POCO types between WCF Data Service and Client Generated by Add Service Reference

I have a WCF Data Service layer that is exposing POCO entities generated by the POCO T4 template. These POCO entities are created in their own project (i.e. Company.ProjectName.Entities) because I'd like to share them wherever possible.
I have a set of interfaces in another project (Company.ProjectName.Clients) that reference these POCO types by adding an assembly reference to the Company.ProjectName.Entities.dll. One of the implementation of these interfaces is a .NET client that I want to consumes the service using the WCF Data Service Client Library.
I've used the Add Service Reference to add service reference. This generated the DataServiceContext client class and the POCO entities that are used by the service. However, these POCO types gemerated by the Add Service Reference utility now have a different namespace (i.e. Company.ProjectName.Clients.Implementation.WcfDsReference).
What that means is that the POCO types defined in the interfaces cannot be used by the types generated by the utility without have to cast or map.
i.e. Suppose I have:
1. POCO Entity: Company.ProjectName.Entities.Account
2. Interface: interface IRepository<Company.ProjectName.Entities.Account>{....}
3. Implementation: ServiceClientRepository : IRepository<Company.ProjectName.Entities.Account>
4. WcfDsReference: Company.ProjectName.Clients.Implementation.WcfDsReference
& Company.ProjectName.Clients.Implementation.WcfDsReference.Account
Let's say I want to create a DataServiceQuery query on the Account, I won't be able to do this:
var client = new WcfDsReference(baseUrl);
var accounts = client.CreateQuery<Company.ProjectName.Entities.Account>(...)
OR: client.AddToAccounts(Company.ProjectName.Entities.Account)
, because the CreateQuery<T>() expects T to be of type & Company.ProjectName.Clients.Implementation.WcfDsReference.Account
What I currently have to do is to pass the correct entity to the CreateQuery method and have to map the results back to the type the interface understands. (Possible with a mapper but doesn't seems like a good solution.)
So the question is, is there a way to get the Add Service Reference utility to generate methods that use the POCO types that are in the Company.ProjectName.Entities namespace?
One solution I am thinking of is to not use the utility to generate the DataServiceContext and other types, but to create my own.
The other solution is to update the IRepository<T> interface to use the POCO types generated by the utility. But this sounds a little bit hacky.
Is there any better solution that anyone has come up with or if there's any suggestion?
Ok, a few hours after starting the bounty I found out why it wasn't working as expected on my end.
It turns out that the sharing process is quite easy. All that needs to be done is mark the model classes with the [DataServiceKey] attribute. This article explains the process quite well, in the 'Exposing another Data Model' section
With that in mind, what I was trying to do is the following:
Placing the model on a separate class library project C, sharing it with both webapplication projects A and B
Create the data service on project A
Add the service reference on project B
Delete the generated model proxies out of the service reference, and update it to use my model classes in project C
Add the DataServiceKey attribute to the models, specifying the correct keys
When I tried this it did not work, giving me the following error:
There is a type mismatch between the client and the service. Type
{MyType} is not an entity type, but the type in the
response payload represents an entity type. Please ensure that types
defined on the client match the data model of the service, or update
the service reference on the client.
This problem was caused by a version mismatch between project C (which was using the stock implementations on the System.Data.OData assemblies) and the client project B that was calling the service (using the Microsoft.Data.OData assemblies in the packages). By matching the version on both ends, it worked the first time.
After all this, one problem remained though: The service reference procedure is still not detecting the models to be shared, meaning proxies are being created as usual. This led me to opt out of the automatic service integration mechanic, instead forcing me to go forward with a simple class of my own to serve as the client to the Wcf Data service. Basically, it's a heavily trimmed version of the normally autogenerated class:
using System;
using System.Data.Services.Client;
using System.Data.Services.Common;
using Model;
public class DataServiceClient : DataServiceContext
{
private readonly Lazy<DataServiceQuery<Unit>> m_units;
public DataServiceClient(Uri _uri)
: base(_uri, DataServiceProtocolVersion.V3)
{
m_units = new Lazy<DataServiceQuery<Unit>>(() => CreateQuery<Unit>("Units"));
}
public DataServiceQuery<Unit> Units
{
get { return m_units.Value; }
}
}
This is simple enough because I'm only using the service in readonly mode. I would still like to use the service reference feature though, potentially avoiding future maintenance problems, as evidenced by the hardcoded EntitySet name in this simple case. At the moment, I'm using this implementation and have deleted the service reference altogether.
I would really like to see this fully integrated with the service reference approach if anyone can share a workaround to it, but this custom method is acceptable for our current needs.

Saving objects in EntityFramework over WCF causes related entities to be created

A couple of times on this current project developers have hit the same problem:
An object with related entities, i.e. an Order with a related Customer is sent back via WCF to entitywork to be saved. If the object is new we use AddObject() to put it back in the context and if it has changed, then we use ApplyCurrentValues() to update the object.
The Order object has changed, but the Customer object has not (unless the streaming via WCF affects it in some way). However, when calling SaveChanges() on the context the main object, Order in this example, is saved, but a new copy of Customer is also added to the database.
The workaround that we have found is to set the reference to Customer on Order to null before calling SaveChanges(), however this feels like a bit of a kludge.
What I'm looking for is the "correct" way to solve this problem, something akin to LazySaving = false, i.e. only save the object changed and don't try to create all the related objects.
Thanks in advance for any pointers.
I am not sure about Entity Framework, but I ran into this issue recently with NHibernate. I solved it by implementing save as follows
(1) Retrieve original entity from DB
(2) Update original entity from WCF Data Transfer object using AutoMapper
(3) Save original entity
I am not sure if you are trying to use your entities as DataContracts, in my experience its always better to use Data Transfer Objects rather than entities as you DataContract. If you dont, you continually run into all kinds of trouble, and DTO+AutoMapper gives you the control to solve most issues that you run into
http://automapper.codeplex.com/

wcf and ADO entity framework

We are using Linq to Entities in WCF service. We created a edmx file which contains auto generated entities. While creating proxy the entities are not appearing in the proxy class even the data contract and datamember attributes are there. We found that the problem is because of the auto generated entities are inheriting from something called System.Data.Objects.DataClasses.EntityObject But if we create a class without any inheritance that class is appearing in the proxy. Is there any way to resolve this?
Regards
Sekar
The way we do this is:
Auto generate entity framework entities
Create separate classes to be used in the data contracts
Write mapping code to convert from one contract classes to entity classes, and back
This may be a bit cumbersom but it works (it also isolates your services from changes in your database). This should become much easier in the next version of entity framework.