开发者

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

开发者 https://www.devze.com 2023-03-06 19:54 出处:网络
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.

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 A开发者_开发技巧pplyCurrentValues() 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/

0

精彩评论

暂无评论...
验证码 换一张
取 消