MVCアプリケーションでEntityFrameworkでリポジトリパターンを使用してレコードを更新しようとしていますが、db.SaveChanges()メソッドがデータベースに保存されません。私はエラーが発生していないので、コードをステップ実行して、正しい変数が渡され、レコード変数が更新されるのを確認することができます。エンティティフレームワークとレコードを更新するMVCリポジトリパターン
私が読んできた内容に基づいて、自分のデータベースコンテキスト(MyDBEntities)のインスタンスが2つあることが問題だと思います。問題は、MyDBEntitiesのインスタンスを作成するReadRepositoryが、MyDBEntitiesインスタンスも作成するWriteRepositoryに挿入されている可能性があります。エンティティをリポジトリに挿入する方法が本当にわかりません(これを想定していると仮定します)。
db.SaveChanges()
の前にdb.MyTable.Attach(record);
のようなものを追加しようとすると、私はMyDBEntities()
を注入する必要があると考えられます。
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
CONTROLLER
public class MyController : Controller
{
private IWriteRepository _writeRepository;
public MyController(IWriteRepository writeRepository)
{
_writeRepository = writeRepository;
}
[HttpPost]
public ActionResult MyPostMethod(MyViewModel model)
{
try
{
//Send to the repository to edit a record
writeRepository.EditRecord(model);
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch
{
throw new HttpException(500, "Internal Server Error");
}
}
}
WRITEリポジトリ
//The ReadRepository is injected into the WriteRepository to grab records from the database
public class WriteRepository : IWriteRepository
{
private MyDBEntities db = new MyDBEntities();
private IReadRepository _readRepository;
public WriteRepository(IReadRepository readeadRepository)
{
_readRepository = readRepository;
}
public void EditRecord(MyViewModel model)
{
//Get the specific record to be updated
var record = readRepository.GetRecord(model.ID);
//Update the data
record.FirstName = model.Name;
//This isn't saving
db.SaveChanges();
}
}
READリポジトリ
01あなたの MyControllerコードからpublic class ReadRepository : IReadRepository
{
private MyDBEntities db = new MyDBEntities();
//Provides the record to the write repository to edit
public MyTable GetRecord(int ID)
{
var record = (from t in db.MyTable
where t.ID == ID
select t).SingleOrDefault();
return record;
}
}
[エンティティオブジェクトの可能な重複はIEntityChangeTrackerの複数のインスタンスによって参照できません。 Entity Framework 4.1のエンティティに関連するオブジェクトを追加しています](http://stackoverflow.com/questions/10191734/entity-object-cannot-be-referenced-by-multiple-instances-ofientitychangetracker) –
私はその1つを読んだしかし、私が探している部分は、リポジトリの外部でデータベースコンテキストを作成する方法を助けます。 – madvora