我想學習LINQ to SQL。我已經成功實現了插入方法,並且數據正在插入到數據庫中。當我嘗試更新現有數據時,即使沒有異常,它也不會反映到數據庫中。你能否介紹一下可能出現的問題?數據庫不會更新與附加方法
注:賬戶號碼是主鍵
編輯
繼使得它的工作的代碼行。但是,你能解釋一下爲什麼我們需要刷新?
accountRepository.UpdateChangesByAttach(acc1);
accountRepository.RefreshEntity(acc1);
accountRepository.SubmitChanges();
注:
DataContext.Refresh method refreshes object state by using data in the database.
刷新與KeepCurrentValues選項來完成。我的理解是它會保留我在實體對象中更新的值。我正在提供(僅)需要在數據庫中更新的所需信息。此刷新是否需要才能獲得剩餘的列值?
客戶
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();
}
業務層
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();
}
庫
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」
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?