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);
}
}
読む