I am trying to learn LINQ to SQL. I have successfully implemented insert method and data is getting inserted into database. When I try to update the existing data, it does not get reflected in the database even though there is no exception. Can you please put some light on what could have gone wrong?
Note: AccountNumber is primary key
EDIT
Following lines of code makes it working. But, can you explain why we need a refresh?
accountRepository.UpdateChangesByAttach(acc1);
accountRepository.RefreshEntity(acc1);
accountRepository.SubmitChanges();
Note:
DataContext.Refresh method refreshes object state by using data in the database.
The refresh was done with KeepCurrentValues option. What I understand is it will retain the values which I updated in the entity object. I am supplying (only) the required information which need to be updated in the database. Is this refresh required to get the remaining column values?
Client
using (var context = new RepositoryLayer.LibraryManagementClassesDataContext(connectionstring))
{
context.Log = Console.Out;
RepositoryLayer.Repository<RepositoryLayer.Account> selectedRepository = new RepositoryLayer.Repository<RepositoryLayer.Account>();
//selectedRepository.Context = context;
AccountBusiness accountBl = new AccountBusiness(selectedRepository);
//Transaction 1
//List<RepositoryLayer.Account> accountList = accountBl.GetAllAccounts();
//Transaction 2
//accountBl.InsertAccounts();
//Transaction3
accountBl.UpdateAccounts();
}
Business Layer
public void InsertAccounts()
{
RepositoryLayer.Account acc1 = new RepositoryLayer.Account();
acc1.AccountNumber = 4;
acc1.AccountType = "Contract";
acc1.Duration = 6;
accountRepository.InsertOnSubmit(acc1);
accountRepository.SubmitChanges();
}
public void UpdateAccounts()
{
RepositoryLayer.Account acc1 = new RepositoryLayer.Account();
acc1.AccountNumber = 4;
acc1.AccountType = "TEST";
acc1.Duration = 10;
accountRepository.UpdateChangesByAttach(acc1);
accountRepository.SubmitChanges();
}
Repository
public class Repository<T> : IRepository<T> where T : class
{
public System.Data.Linq.DataContext Context
{
get;
set;
}
public virtual System.Data.Linq.ITable GetTable()
{
return Context.GetTable<T>();
}
public virtual void InsertOnSubmit(T entity)
{
GetTable().InsertOnSubmit(entity);
}
public virtual void UpdateChangesByAttach(T entity)
{
GetTable().Attach(entity);
}
public virtual void SubmitChanges()
{
Context.SubmitChanges();
}
public virtual void RefreshEntity(T entity)
{
Context.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, entity);
}
}
READING
LINQ to SQL: Updating without Refresh when “UpdateCheck = Never”
Linq To SQL Attach/Refresh Entity Object
What does LINQ-to-SQL Table<T>.Attach do?
Why should I use GetOriginalEntityState() in my LINQ To SQL repository save method?
How can I reject all changes in a Linq to SQL's DataContext?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…