I have the following code for updating Account table with LINQ to SQL. AccountNumber is the primary key column. The only value which need to be updated is AccountType; howev
I solved this issue by changing the update approach by following the answer in LINQ to SQL: Updating without Refresh when “UpdateCheck = Never”
UpdateCheck is set as Never for the Duration column
public void UpdateAccount()
{
//Used value from previous select
DateTime previousDateTime = new DateTime(2012, 6, 26, 11, 14, 15, 327);
int prevDuration = 0;
RepositoryLayer.Account accEntity = new RepositoryLayer.Account();
accEntity.AccountNumber = 1; //Primary Key
accEntity.ModifiedTime = previousDateTime; //Concurrency column
//accEntity.Duration = prevDuration;
accountRepository.UpdateChangesByAttach(accEntity);
//Values to be modified after Attach
accEntity.AccountType = "WIN-WIN";
accEntity.ModifiedTime = DateTime.Now;
try
{
accountRepository.SubmitChanges();
}
catch(System.Data.Linq.ChangeConflictException e)
{
throw new Exception(e.Message);
}
}
public virtual void UpdateChangesByAttach(T entity)
{
if (Context.GetTable<T>().GetOriginalEntityState(entity) == null)
{
//If it is not already attached
Context.GetTable<T>().Attach(entity);
}
}
Generated SQL
UPDATE [dbo].[Account]
SET [AccountType] = @p2, [ModifiedTime] = @p3
WHERE ([AccountNumber] = @p0)
AND ([ModifiedTime] = @p1)
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input DateTime (Size = -1; Prec = 0; Scale = 0) [6/26/2012 11:14:15 AM]
-- @p2: Input NChar (Size = 10; Prec = 0; Scale = 0) [WIN-WIN]
-- @p3: Input DateTime (Size = -1; Prec = 0; Scale = 0) [6/26/2012 11:16:29 AM]
This should do:
int number = 4;
var acc1 = new accountRepository.Accounts.Where(a => a.Number == number).FirstOrDefault();
if (acc1 == null)
{
// Not found by ID, create new
acc1 = new RepositoryLayer.Account();
acc1.Number = number;
accountRepository.Accounts.AddObject(acc1);
}
acc1.AccountType = "Verify";
accountRepository.SubmitChanges();