none
Creating a new record, NotSupportedException RRS feed

  • Question

  • Hey everyone, perhaps you can help shed some light on this issue I'm having. When I try to save a new record using the code below I'm getting the following exception:

    NotSupporedException

    An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.  This is not supported.

    Here is the code I'm using to create my record. Please note that the data context is populated via the factory and the same data context object is applied to all repository objects created by the factory (ironically this temporarily solved the same problem I'm encountering now for another scenario).

    Edit: The code formatter here is of pretty poor quality. I've pasted the relevant code in pastebin: http://pastebin.com/zFD9xupL

    If you need any further information please let me know!

    Thanks,

    • Edited by Brad Heller Friday, April 9, 2010 12:44 AM Moved code
    Friday, April 9, 2010 12:15 AM

Answers

  • There are a few different workarounds for that:

    1) Instead of assigning the Organization object, just set the column(s) used for the foreign key to organization, e.g. OrganisationID.

    ...or...

    2) If you have a timestamp/rowversion column in the table, you can detach the organization object from the datacontext it came from and reattach it to a new DC without getting the 'loaded from another datacontext' exception. The key is that detach/attach across DCs works a lot better if there is a timestamp/rowversion since L2S can then use that for concurrency checks.

    ...or...

    3) Create a in-memory-clone of the Organization object, copy member values across (e.g. using reflection). Has the potential of confusing L2S that the organization is actually a new record to be inserted in the DB, so can result in constraint violations when submitting changes.

    ...or...

    4) Reload the organization object from the db on the new DC, and attach that. (unnecessary additional roundtrip to the db)

    (1) is probably the easiest to do, while (2) is more flexible and (3)/(4) are more of fallback scenarios if 1 or 2 can't be used.


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for the L2S and EF designers in VS2008 and VS2010)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Friday, April 9, 2010 5:00 AM
    Answerer
  • This is interesting, it kind of implies to me that it's better to just detach everything you're returning from a load operation and attach everything you're sending back to the DB and only stay attached while the DC object is in scope (i.e. detach before returning from a save operation). Do you think that this is true?


    Yes. But to be able to do that without requerying etc you need to have a timestamp/rowversion column that L2S can use for update checks. (It is possible without, but then requires requerying the db when re-attaching...)
    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for the L2S and EF designers in VS2008 and VS2010)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Friday, April 9, 2010 6:14 AM
    Answerer

All replies

  • Besides setting the scalar members as per the code sample provided, do you set any navigation properties / associations before saving? Could it be that some associated object has been loaded by another DC instance?


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for the L2S and EF designers in VS2008 and VS2010)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Friday, April 9, 2010 2:28 AM
    Answerer
  • Hello Brad,

     

    Welcome to LINQ to SQL forum!

     

    Based on your code snippet, I don’t see any clue which shows the User entity is tracked by another DataContext.  But based on my test, the DataContext.User.Contains(user) will generate such a SQL statements to query the database if the Id is the primary key of the User table:

    ==============================================================================

    SELECT

        (CASE

            WHEN EXISTS(

                SELECT NULL AS [EMPTY]

                FROM [dbo].[User] AS [t0]

                WHERE [t0].[id] = @p0

                ) THEN 1

            ELSE 0

         END) AS [value]

    ==============================================================================

    The @p0 parameter should be the default value of the GUID (zero).  

     

    For the NotSupportedException, could you please send me a demo project and db file to repro it, if it is convenient for you.    My mail address is v-micsun@microsoft.com.   Thanks a lot!

     

    Have a nice weekend!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, April 9, 2010 2:37 AM
    Moderator
  • Hey Lingzhi, 

    Thanks for your quick reply! I created a test application as you requested but I was unable to reproduce the error in the test application!

    I set up a similar object model (two tables with a one -> many relationship) and was able to create a parent object and then two child objects without issue, so I don't think it has anything to do with the relationships as KristoferA mentions above (I think that's what he means, thanks for you suggestion though KristoferA!).

    Are there perhaps any known issues around default values for columns in databases? Any further guidance you guys can provide would be amazing!

    Thanks,

    Brad Heller

    Friday, April 9, 2010 3:32 AM
  • Hey KristoferA,

    Thanks for your response! Good question. For what it's worth, the Organization property in the snippet referenced above is, in the data model, a foreign key in to an "Organization" table. I touched on this below in my response to Lingzhi Sun. The Organization object in question here, though, is not loaded via a different DC...although, now that I'm typing this, I think it might be. The organization object in this case is stored in Session (this is being consumed by an ASP.NET application) and, when this is set, it's retrieved from session and assigned to this property.

    Do you think that this is the issue, perhaps? If so, do you know of a reasonable workaround -- perhaps a way to tell if an object is attached to a data context (as I don't want to always attach to the Organization object in this method)?

    Thanks,

    Brad Heller

    Friday, April 9, 2010 3:47 AM
  • There are a few different workarounds for that:

    1) Instead of assigning the Organization object, just set the column(s) used for the foreign key to organization, e.g. OrganisationID.

    ...or...

    2) If you have a timestamp/rowversion column in the table, you can detach the organization object from the datacontext it came from and reattach it to a new DC without getting the 'loaded from another datacontext' exception. The key is that detach/attach across DCs works a lot better if there is a timestamp/rowversion since L2S can then use that for concurrency checks.

    ...or...

    3) Create a in-memory-clone of the Organization object, copy member values across (e.g. using reflection). Has the potential of confusing L2S that the organization is actually a new record to be inserted in the DB, so can result in constraint violations when submitting changes.

    ...or...

    4) Reload the organization object from the db on the new DC, and attach that. (unnecessary additional roundtrip to the db)

    (1) is probably the easiest to do, while (2) is more flexible and (3)/(4) are more of fallback scenarios if 1 or 2 can't be used.


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for the L2S and EF designers in VS2008 and VS2010)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Friday, April 9, 2010 5:00 AM
    Answerer
  • you can detach the organization object from the datacontext it came from and reattach it to a new DC without getting the 'loaded from another datacontext' exception. The key is that detach/attach across DCs works a lot better if there is a timestamp/rowversion since L2S can then use that for concurrency checks.

    This is interesting, it kind of implies to me that it's better to just detach everything you're returning from a load operation and attach everything you're sending back to the DB and only stay attached while the DC object is in scope (i.e. detach before returning from a save operation). Do you think that this is true?

    Thanks,

    Brad Heller

    Friday, April 9, 2010 5:29 AM
  • This is interesting, it kind of implies to me that it's better to just detach everything you're returning from a load operation and attach everything you're sending back to the DB and only stay attached while the DC object is in scope (i.e. detach before returning from a save operation). Do you think that this is true?


    Yes. But to be able to do that without requerying etc you need to have a timestamp/rowversion column that L2S can use for update checks. (It is possible without, but then requires requerying the db when re-attaching...)
    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for the L2S and EF designers in VS2008 and VS2010)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Friday, April 9, 2010 6:14 AM
    Answerer
  • Hi Brad,

     

    I am writing to check the status of the issue on your side.  Could you please tell us how is the problem now?  

     

    If you need further assistance, please feel free to let me know.  I will be more than happy to be of assistance.

     

    Have a nice weekend!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Supportin Forum

    If you have any feedback on our support, please contactmsdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, April 16, 2010 1:28 AM
    Moderator