2012-01-25 8 views
1

MVCとEntity Frameworkコードファーストを使用してアプリケーションを構築しています。ASP.NET MVCコード最初に重複レコードを作成する

私は、モデルの変更によってデータベースが再作成されたときに、初期化子を使用してデータベースを設定しています。

私はEFコードで問題が発生しています。重複レコードを最初に作成しています。説明する最も簡単な方法は、自分のコードを表示することです。

// 
    // POST: /Incident/CreateIncident 
    [HttpPost] 
    public ActionResult CreateIncident(IncidentViewModel model) 
    { 
     Incident incidentToAdd = new Incident(); 

     // Record incident details 
     incidentToAdd.Caller = repository.GetDomainUser(model.selectedCaller); 
     incidentToAdd.CallerType = model.Incident.CallerType; 
     incidentToAdd.Service = repository.GetService(model.selectedService); 
     incidentToAdd.Category = repository.GetCategory(model.selectedCategory); 
     incidentToAdd.AllocatedTo = repository.GetHelpDeskMember(model.selectedAllocatedTo); 

     [Rest of code omitted to save space] 

     // TODO: Send Email to Caller and AllocatedTo 

     // Store incident in database 
     db.Incidents.Add(incidentToAdd); 
     db.SaveChanges(); 

     return RedirectToAction("Index"); 
    } 

私は、リポジトリから既存のサービス、カテゴリーやAllocatedToを取得していますが、それは代わりになど、既存のサービスカテゴリにリンクする、レコードを保存するために来るとき、それは新しいレコードを作成します既存のものの複製。

私は本当にそれをうまく説明しませんでした。しかし、もしあなたが何か助けを与えることができればそれは大いに感謝されるでしょう。

ありがとうございました。

+0

が実際にDbContextに添付されていない事件でのサービスとカテゴリレコードのような音:

Service service = repository.GetService(model.selectedService); incidentToAdd.Service = service; db.Entry(service).State = EntityState.Unchanged; Category category = repository.GetCategory(model.selectedCategory); incidentToAdd.Category = category; db.Entry(category).State = EntityState.Unchanged; HelpDeskMember allocatedTo = repository.GetHelpDeskMember(model.selectedAllocatedTo); incidentToAdd.AllocatedTo = allocatedTo; db.Entry(allocatedTo).State = EntityState.Unchanged; 

私は、このリンクでは、ここで情報を見つけました。リポジトリで使用されるDbContextがコントローラ内のDbContextと異なるか、リポジトリがデタッチされたエンティティを返すかのいずれかです。 repositry.GetServiceは、コントローラーと同じDbContextを使用しているかのように見えますか? – Leniency

+0

@Leniency、Yesリポジトリとコントローラはまったく同じコンテキストを使用しています。 GetService()メソッドは次のようになります。 'public Service GetService(int id) { return db.Services.SingleOrDefault(s => s.ServiceID == id); } ' –

答えて

1

私はこの問題を解決しました。私はそれが正しい方法であるかどうかはわかりませんが、私が望む結果を得ています。

データベースから返されたエンティティを単にincidentToAddに追加するのではなく、EntityStateを使用してエンティティを変更しないで指定します。 Using DbContext in EF 4.1 Part 4: Add/Attach and Entity States

関連する問題