none
Adding AND Modifying on a detached Entity Object RRS feed

  • Question

  • In the EF 4.1, is there a simple way to add/attach disconnected entity graphs that may be both modified and added to? Or, if not, does anyone have an already existing extension method that does so?

    I've seen previous discussions on this topic, but they were all years old. It's a total pain (and a waste of development time) to manually separate modified from new objects each time this situation arises and having to decide whether to use Add or Attach.

    I have something akin to the following logic (greatly oversimplified):

     

                ICollection<Report> storedReports;
    
                using (var context = new MyEntityContext())
                {
                    storedReports = context.Reports;
                }
    
                //...Sometime later, as a result of user actions through the GUI...
    
                report.date = new DateTime(11, 11, 11);
                report.Suppliers.Add(new Supplier
                {
                    firstName = "Bugs",
                    lastName = "Bunny"
                });
    
    reports.Add(report);

    //...Sometime later, when the user clicks "Save"...
    //I now need to persist this new data to the database using (var newContext = new MyEntityContext()) {
    foreach(var report in storedReports)
    {
     //I need something like this newContext.Reports.AddOrAttach(report);
    }
    }

    Thanks for any help.

     



    • Edited by MgSm88 Friday, October 28, 2011 8:29 PM
    Friday, October 28, 2011 8:26 PM

All replies

  • Hi MgSm88,

    I think can test this method:

    ---------------------------------

    Insert or update pattern

    A common pattern for some applications is to either Add an entity as new (resulting in a database insert) or Attach an entity as existing and mark it as modified (resulting in a database update) depending on the value of the primary key. For example, when using database generated integer primary keys it is common to treat an entity with a zero key as new and an entity with a non-zero key as existing. This pattern can be achieved by setting the entity state based on a check of the primary key value. For example:

    public void InsertOrUpdate(DbContext context, Unicorn unicorn)
    {
        context.Entry(unicorn).State = unicorn.Id == 0 ?
                                       EntityState.Added :
                                       EntityState.Modified;
        context.SaveChanges();
    }

    ------------------------------------

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, November 1, 2011 7:38 AM
    Moderator
  • Thanks for the response.

    I've seen this method before, however, I have two issues with it:

    a) I'm doing database-first development, so I have an ObjectContext, not a DbContext, and thus the context.Entry() method is not available and a more ugly call into the ObjectStateManager is required to change the state.

    b) It's kind of a hack that is relying upon the default value of the id being zero. Isn't one of the main features of an ORM to have robust object state tracking so that you don't have to worry about low level stuff like this? Because this relies upon there being an id property, it also makes it impossible to encapsulate in an extension method.

    The EF has been around for quite a while now and based on all the historical posts I've read, this is such a common issue I'd have thought there would be a solution baked in by now.

    Tuesday, November 1, 2011 2:40 PM
  • Hi,

    Thanks for your feedback.

    My mistake, DbContext is in EF4.1. This is the only way to change the entities' states in EF4 by ObjectStateManager.

    Thanks for your suggestion:

    --------------------

    When a new entity is created, the Entity Framework defines temporary key and sets the IsTemporary property to true. When you call the SaveChanges method, the Entity Framework assigns a permanent key and sets the IsTemporary property to false.

    http://msdn.microsoft.com/en-us/library/dd283139.aspx

    --------------------

    Have a nice day.

     


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, November 3, 2011 8:10 AM
    Moderator