locked
Add an object and some of it's relationships RRS feed

  • Question

  • Hi,

    I have an app with EntityFramework and the Repository Pattern.

    I am trying to add a new object to the Database. That object has relationships and these relationships have relationships of their own. Some of them are new to the Database and need to be inserted and some are already there.

    The problem is that if I use the Add method like this:

      public void Add(params T[] items)
            {
                using (var context = new TTContext())
                {
                    foreach (T item in items)
                    {
                        context.Entry(item).State = EntityState.Added;
                    }
    
                    context.SaveChanges();
                }                                                 
            }

    The whole relationship is added, including objects that had a PK set.

    I understand that I can use the Attach method to prevent such a situation but then I face a different problem. The newly created relationships are not aware of the object's PK and therefore cannot be inserted and an exception is thrown. Also, I can't use the Attach method in the generic method above since Attach belongs to a specific Dbset.

    So is there a way to add a new object with relationships that some exist in the Database and some don't? How can I make this generic?

    Thank you!

    EDIT:

    For now I found a workaround but i'm sure there is a better solution.

    The workaround is manually setting the relationship collections that I don't want inserted to the Database to null and then still use the Add method like the above example.


    • Edited by Tomer Agmon Saturday, February 13, 2016 5:18 PM
    Saturday, February 13, 2016 3:41 PM

Answers

  • So is there a way to add a new object with relationships that some exist in the Database and some don't? How can I make this generic?

    What would you do if EF was not there and you where using T-SQL in a sproc that was doing this for you?

    1) add the parent object via EF that returns the primary-key back to the object when inserted.

    2) take the primary-key from the parent object and hold on to it in variable.  

    3) add each child object populating the child's foreign-key property from the parent's primary-key variable. 

    Sometimes, one has to take control.

    • Marked as answer by Tomer Agmon Sunday, February 14, 2016 5:55 AM
    Saturday, February 13, 2016 9:12 PM