0

以下に示すように、リポジトリクラス内に次のメソッドがあり、Sessionオブジェクトと関連するものを取得しますMedicine object(を使用してEagerの読み込みを定義することにより.Include):-

public Session GetSession(int id)
        {
            return entities.Sessions.Include(d => d.Medicine).FirstOrDefault(d => d.SessionID == id);

        }

上記のリポジトリメソッドを呼び出す私のアクションメソッドは次のようになります:-

[HttpPost]
        public ActionResult Delete(int id)
        {

            try
            {
                //string desc;
                var s = repository.GetSession(id);

                repository.DeleteSession(s);

                repository.Save();
                return Json(new { IsSuccess = "True", id = s.SessionID, description = s.Medicine.Name }, JsonRequestBehavior.AllowGet);
            }
            catch (ArgumentNullException)
//code goes here

私が直面している問題は、を使用してオブジェクトを物理的に削除した後 、メモリからrepository.Save();にアクセスできなくなり、次の例外が発生することです。NullReferenceExceptionは、のユーザーコードによって処理されませんでしたが、使用可能なにアクセスできます。オブジェクトを削除した後でもメモリ内にあるので、これは、削除されたオブジェクトがナビゲーションプロパティを(熱心にロードしなかった)しなかったことを意味します!!!?BRMedicine navigation propertydescription = s.Medicine.Names.SessionIDSessionIncludeMedicine

4

1 に答える 1

1

別のエンティティと関係のあるエンティティを削除すると、EntityFrameworkはそれらのオブジェクト間の関係を同時に削除します。エンティティを削除するに、Json結果のオブジェクトを作成することで、問題を解決できます。

var s = repository.GetSession(id);

var result = new { IsSuccess = "True", id = s.SessionID,
                   description = s.Medicine.Name };

repository.DeleteSession(s);
repository.Save();

return Json(result, JsonRequestBehavior.AllowGet);

データベースにセッションからMedicineへの参照がない場合Include、関連するオブジェクトが返されないため、これはもちろん役に立ちません。このケースは個別に処理する必要があります(関係が必要ない場合にのみ可能です)。

于 2012-04-30T22:42:34.417 に答える