WCF Data Services saving relational entities
I'm trying to save an object back to the database via WCF, like so (pseudo code):
var Contact = new Contact
{
Id = Guid.NewGuid(),
Name = "Test",
Address = new Address
{
Id = Guid.NewGuid(),
Postcode = "blah"
}
};
In my model the relationship is 1 to 1 with Conta开发者_开发百科ct and Address but doing this fails:
DB.AddToContacts(Contact);
DB.SaveChanges();
Complaining the relationship isn't met and can't be empty. So I tried this approach:
DB.AddToContacts(Contact);
DB.AddToAddresses(Contact.Address);
DB.AddRelatedObject(Contact, "Address", Contact.Address);
DB.SaveChanges();
but now I get "AddRelatedObject method only works when the sourceProperty is a collection.".
My question: how do I save back a related entity easily via WCF?
This might not be the best answer, but it worked for me... When trying to create an related object in WCF Data Services, you have to set the "back-reference" manually ( this is where the behaviour differs from the normal usage of EF )..
So, in your case you would have to set sth like:
var Contact = new Contact
{
Id = Guid.NewGuid(),
Name = "Test",
Address = null
};
var address = new Address
{
Id = Guid.NewGuid(),
Postcode = "blah",
// This is important
Contact = Contact
};
contact.Address = address;
DB.AddToContracts(Contract);
DB.SaveChanges();
This is pretty annoying... And as i got this experience the "hard" way.. WCF Data Services is slow as s**t and selecting hierarchical data ( such as Order - OrderPosition - Product ) is a real pain... you may consider using sth. different for latency-relevant scenarios...
I finally got it to work by doing this:
DB.AddToAddresses(Client.Address);
DB.AddToClients(Client);
DB.SetLink(Client, "Address", Client.Address);
DB.SaveChanges();
That is 4 individual calls over the wire to the WCF service to add a relational object. At the end of it all I'll be making 14 calls, eek!
精彩评论