Saving Disconnected Entities with Linq2SQL

I struggled yesterday with saving modified entities back to the database after they were disconnected from their original DataContext. After much googling, I found the way forward is to ensure you have a version column in your database with a timestamp datatype, and map this with a Binary field in your mapping metadata. Then you can call an overload of Attach.

A complete working example below, as simple as I can make it. Hope that helps somebody.

using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using NUnit.Framework;

namespace CustomerSaver
{
    [TestFixture]
    public class Class1
    {
        [Test]
        public void TrySaveCustomer()
        {
            const string connectionString = @"server=.\SqlExpress; database=test;trusted_connection=true";
            Customer customer;

            using(DataContext readContext = new DataContext(connectionString))
            {
                customer = readContext.GetTable().First();
            }

            customer.Name = customer.Name + ".";
            using (DataContext saveContext = new DataContext(connectionString))
            {
                saveContext.GetTable().Attach( customer, true );
                saveContext.SubmitChanges();
            }
        }
    }

    [Table(Name="Customers")]
    public class Customer
    {
        [Column(IsPrimaryKey = true)]
        public int Id { get; set; }

        [Column]
        public string Name { get; set; }

        [Column(IsVersion = true, IsDbGenerated = true)]
        public Binary Version { get; set; } //timestamp column in sql server
    }
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
This entry was posted in Uncategorized. Bookmark the permalink.