Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 409751
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T17:49:17+00:00 2026-05-12T17:49:17+00:00

I have a Linq object, and I want to make changes to it and

  • 0

I have a Linq object, and I want to make changes to it and save it, like so:

public void DoSomething(MyClass obj) {
  obj.MyProperty = "Changed!";
  MyDataContext dc = new MyDataContext();
  dc.GetTable<MyClass>().Attach(dc, true); // throws exception
  dc.SubmitChanges();
}

The exception is:

System.InvalidOperationException: An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.

It looks like I have a few choices:

  1. put a version member on every one of my Linq classes & tables (100+) that I need to use in this way.
  2. find the data context that originally created the object and use that to submit changes.
  3. implement OnLoaded in every class and save a copy of this object that I can pass to Attach() as the baseline object.
  4. To hell with concurrency checking; load the DB version just before attaching and use that as the baseline object (NOT!!!)

Option (2) seems the most elegant method, particularly if I can find a way of storing a reference to the data context when the object is created. But – how?

Any other ideas?

EDIT

I tried to follow Jason Punyon’s advice and create a concurrency field on on table as a test case. I set all the right properties (Time Stamp = true etc.) on the field in the dbml file, and I now have a concurrency field… and a different error:

System.NotSupportedException: 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.

So what the heck am I supposed to attach, then, if not an existing entity? If I wanted a new record, I would do an InsertOnSubmit()! So how are you supposed to use Attach()?

Edit – FULL DISCLOSURE

OK, I can see it’s time for full disclosure of why all the standard patterns aren’t working for me.

I have been trying to be clever and make my interfaces much cleaner by hiding the DataContext from the “consumer” developers. This I have done by creating a base class

public class LinqedTable<T> where T : LinqedTable<T> {
  ...
}

… and every single one of my tables has the “other half” of its generated version declared like so:

public partial class MyClass : LinqedTable<MyClass> {
}

Now LinqedTable has a bunch of utility methods, most particularly things like:

public static T Get(long ID) {
  // code to load the record with the given ID
  // so you can write things like:
  //   MyClass obj = MyClass.Get(myID);
  // instead of:
  //   MyClass obj = myDataContext.GetTable<MyClass>().Where(o => o.ID == myID).SingleOrDefault();
}
public static Table<T> GetTable() {
  // so you can write queries like:
  //   var q = MyClass.GetTable();
  // instead of:
  //   var q = myDataContext.GetTable<MyClass>();
}

Of course, as you can imagine, this means that LinqedTable must somehow be able to have access to a DataContext. Up until recently I was achieving this by caching the DataContext in a static context. Yes, “up until recently”, because that “recently” is when I discovered that you’re not really supposed to hang on to a DataContext for longer than a unit of work, otherwise all sorts of gremlins start coming out of the woodwork. Lesson learned.

So now I know that I can’t hang on to that data context for too long… which is why I started experimenting with creating a DataContext on demand, cached only on the current LinqedTable instance. This then led to the problem where the newly created DataContext wants nothing to do with my object, because it “knows” that it’s being unfaithful to the DataContext that created it.

Is there any way of pushing the DataContext info onto the LinqedTable at the time of creation or loading?

This really is a poser. I definitely do not want to compromise on all these convenience functions I’ve put into the LinqedTable base class, and I need to be able to let go of the DataContext when necessary and hang on to it while it’s still needed.

Any other ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T17:49:17+00:00Added an answer on May 12, 2026 at 5:49 pm

    The “An entity can only be attached as modified without original state if it declares a version member” error when attaching an entitity that has a timestamp member will (should) only occur if the entity has not travelled ‘over the wire’ (read: been serialized and deserialized again). If you’re testing with a local test app that is not using WCF or something else that will result in the entities being serialized and deserialized then they will still keep references to the original datacontext through entitysets/entityrefs (associations/nav. properties).

    If this is the case, you can work around it by serializing and deserializing it locally before calling the datacontext’s .Attach method. E.g.:

    internal static T CloneEntity<T>(T originalEntity)
    {
        Type entityType = typeof(T);
    
        DataContractSerializer ser =
            new DataContractSerializer(entityType);
    
        using (MemoryStream ms = new MemoryStream())
        {
            ser.WriteObject(ms, originalEntity);
            ms.Position = 0;
            return (T)ser.ReadObject(ms);
        }
    }
    

    Alternatively you can detach it by setting all entitysets/entityrefs to null, but that is more error prone so although a bit more expensive I just use the DataContractSerializer method above whenever I want to simulate n-tier behavior locally…

    (related thread: http://social.msdn.microsoft.com/Forums/en-US/linqtosql/thread/eeeee9ae-fafb-4627-aa2e-e30570f637ba )

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a LINQ query that returns some object like this... var query =
I have a Linq query that returns an object of the type IQueryable<ClassX> .
What is the format for databinding to a complex object? I have a linq
I have a problem using Linq to NHibernate to load an object and eagerly
Currently I have a DataModel object which contains my linq to sql classes(a dmbl
I have an object allStudents = Dictionary<ClassRoom, List<Student>>() In Linq how would I get
I have a DataTable object. Every column is of type string. Using LINQ, how
I'm using linq to pull back an object (i.e. customer) that might have a
How can I use LINQ to achieve the following? I have some c# object
I have a List of classes in my collection like List<MyClass> test = new

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.