This is a migrated thread and some comments may be shown as answers.

Add/Remove Not Working

1 Answer 50 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Joshua
Top achievements
Rank 1
Joshua asked on 15 Oct 2012, 03:45 PM
I am having an issue where the OA is saving an new item that has been removed.  I am using OpenAccess, version 2012.2.816.1, in ASP.NET 3.5.

There is a parent/child relationship of App/Plans.  The collection Plans in app has the IsManaged property set to true, per the development instructions.  The following code snippet is executed:

app.Plans.Add(newPlan);
app.Plans.Remove(newPlan);

When SaveChanges is called on the context object, the context still thinks the newPlan object should be saved, but the save fails because it correctly does not set the foreign key property.  The issue here is the save should not happen on newPlan because it was removed.

1 Answer, 1 is accepted

Sort by
0
Doroteya
Telerik team
answered on 16 Oct 2012, 09:05 AM
Hello Joshua,

This is the expected behaviour of Telerik OpenAccess ORM in case of adding and removing a new object from a collection property of an existing one.

Generally, when you have created a new object and execute the first line from your code snippet, OpenAccess takes care for setting the value of the foreign key of the new object. That means that the new object is added to the context indirectly, in addition to being added to the collection. 

When you execute the second line of the snippet, OpenAccess removes the relationship between the two objects. The new object, however, is still in the context and OpenAccess will try to persist it in the database when you call SaveChanges(). And since the value of the foreign key of the new object cannot be NULL, the code throws an exception.

To actually prevent adding the new object to the database you have to call context.Delete(newObject), before you try context.SaveChanges().

Note that this is applicable only in the case you describe. If you want to implement some other scenario, tell us about it and we will offer you the appropriate solution.

More information about the lifecycle of the objects is available here and here.

If you have any other questions, do not hesitate to get back to us.


Kind regards,
Doroteya
the Telerik team
Telerik OpenAccess ORM Meets ASP.NET Web API. Read more.
Tags
Development (API, general questions)
Asked by
Joshua
Top achievements
Rank 1
Answers by
Doroteya
Telerik team
Share this question
or