how to update easily an entity directly from a wcf call?
This is what I Have in my WCF service
public long Generic_Save(Product p, ObjectSet os)
{
if (p.Id == 0)
{
os.AddObject(p);
}
else
{
// UPDATE
Product original = os.Single<Project>(o => o.Id == p.Id);
original.Name = p.Name;
original.Items = p.Items; // doesn't work !
}
dataEntities.SaveChanges();
return p.Id;
}
Product p
is an object from the WCF Call, with an EntityKey etc.. but it's not attached to the current dataEntities..
What I want to do is to save the object Product p
directly, not to get the original from the ObjectSet os
before and modify the values -> Product original = os.Single<Project>(o => o.Id == p.Id);
How can I do that?
[EDIT]
I have try this to add new items and it's working
foreach (Item item in p.Items)
{
try
{
dataEntities.Items.ApplyCurrentValues(item);
}
catch (Exception)
{
Items i = new Items();
// Set prop here or make a method CopyTo()
i.Prop = item.开发者_JAVA技巧Prop;
dataEntities.AddToItems(i);
}
}
dataEntities.SaveChanges();
Badly. It is possible only with Product p
itself (update detached entity) but it is really hard with items. The problem is that you must manually say EF exactly which item has changes, which is new and also which were deleted. The longer discussion of the problem is here. Common solutions are:
- Do it exactly as you did at the moment but instead of assigning items, manually compare original and received items and modify loaded items accordingly. If you do not add or remove items on the client this should be just about calling
ApplyCurrentValues
for each item. - Use Self tracking entities (only for .NET clients).
精彩评论