我正在尝试学习 LINQ to SQL。我已经成功实现了插入方法,并且数据正在插入数据库中。当我尝试更新现有数据时,即使没有异常,它也不会反映在数据库中。你能说明一下可能出了什么问题吗?
注意:AccountNumber 是主键
编辑
以下代码行使其工作。但是,你能解释一下为什么我们需要刷新吗?
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);
}
}
阅读