Mats Hofman
Mats Hofman

Reputation: 7240

WCF Data Service - Add Object With Related Object

I have the following situation, I have a WCF Data Service with User objects and message objects and the message object has two relations to user, a sender and a receiver.

When I try to add a new Message object the related users are left null

Message message = new Message();
message.text = InputText; // string
message.Sender = Sender; // User object
message.Receiver = Receiver; // User object

context.AddToMessages(message);
context.BeginSaveChanges(new AsyncCallback((result) => 
{ 
    // Some code 
}));

Now the Sender and Receiver will be null. When I try to set a link before the BeginSaceChanges like this I get the error "InvalidOperationException: The context is not currently tracking the entity."

context.AddToMessages(message);
context.AddLink(message, "Sender", message.Sender);
context.AddLink(message, "Receiver", message.Receiver);
context.BeginSaveChanges(new AsyncCallback((result) => 
{ 
    // Some code 
}));

How do I make sure the relations are created properly?

Upvotes: 1

Views: 469

Answers (2)

Mats Hofman
Mats Hofman

Reputation: 7240

Thanks to Pratik I found the solution. I had to use attach the already existing users Sender and Receiver to the context first because they weren't tracked (and added a if if they are on the second call). Then I add the message and use SetLink to set the link to both users (instead of AddLink)

if(context.GetEntityDescriptor(message.Sender) == null)
    context.AttachTo("Users", message.Sender);
if (context.GetEntityDescriptor(message.Receiver) == null)
    context.AttachTo("Users", message.Receiver);
context.AddToMessages(message);
context.SetLink(message, "Sender", message.Sender);
context.SetLink(message, "Receiver", message.Receiver);
context.BeginSaveChanges(new AsyncCallback((result) => 
{ 
    // Some code 
}));

Upvotes: 1

Sebazzz
Sebazzz

Reputation: 1373

I believe you need to use the DbSet.Attach method instead. I assume you use Entity Framework on the back end here.

Upvotes: 0

Related Questions