これは私の最初の質問です。Entity Framework v4 - 2つのオブジェクト間の関係は、異なるObjectContextオブジェクトにアタッチされているため、定義できません
まず最初に、このトピックに関する多くの疑問があることを知っています。さまざまなソリューションを無駄に試してみたと思いますが、基本的なものが不足している可能性があります。
私はasp.net MVC WebアプリケーションでEF4を使用していますが、それ以外のことはわかっていません。
これまでのところ、1つのコンテキスト "db"のみを使用していると言います。 "using"ステートメントを使用していないため、コンテキストが廃棄されていることはわかりませんが、上記の同じエラーを犯し続けてください。
状況は次のとおりです。ClaimGroup(下記参照)を介してレポートに接続された「クレーム」に基づいてメインモデル「レポート」に接続されたエントリ「ReportSections」のバッチを作成するアクション結果があります。
したがって、私の(簡略化した)クラスは次のようになります。
public partial class Claim
{
public Claim()
{
this.ReportSections = new HashSet<ReportSection>();
this.Reports = new HashSet<Reports>();
}
public int id {get; set;}
//other stuff
public virtual ICollection<Reports> Reports {get; set;}
public virtual ICollection<ReportSections> ReportSections {get; set;}
}
public partial class ClaimGroup
{
public ClaimGroup()
{
this.Claims = new HashSet<Claims>();
}
public int id {get; set;}
//other stuff
public virtual ICollection<Claims> Claims {get; set;}
public virtual ICollection<ReportSections> ReportSections {get; set;}
}
public partial class Report
{
public Report()
{
this.ReportSections = new HashSet<ReportSection>();
}
public int id {get; set;}
public int ClaimGroupId {get; set;}
//other stuff
public virtual ICollection<ReportSections> ReportSections {get; set;}
public virtual ClaimGroup ClaimGroup {get; set;}
}
public partial class ReportSection
{
public int id {get; set;}
public int ClaimId {get; set;}
public int ReportId {get; set;}
public int Position {get; set;}
//other stuff
public virtual Report Report {get; set;}
public virtual Claim Claim {get; set;}
}
[誤解を避けるために、私はそれがサイトの他の領域において機能としてクレームとClaimGroups間の多対多の関係がOKに動作していることをうれしく思います。]
私のコントローラは、その後持っています以下;
public ActionResult BuildSections(int id)
{
Report r = db.Reports.Find(id);
int i = 0;
foreach(Claim c in r.ClaimGroup.Claims)
{
r.ReportSections.Add(new ReportSection { Claim = c, Position = i});
i++;
}
db.SaveChanges();
}
複雑なように見えないので、本当に刺激的ですが、私は間違ったことをしています。
ありがとうございます。
Syの
例では、ここでそれは私が持っている解決策を見つけるために私の様々な試みで、しかし
db.SaveChanges();
上にあるので、エラーが戻ってデータベースに保存するにトリガEDIT
試してみました
db.ReportSections.Add(new ReportSection {...});
その行にエラーが発生しました。
エラーが追加?次のように変数にReportSectionを追加してみてください: 'var rs = new ReportSection {[..]}; db.ReportSections。追加(rs); ' – Max
マックス - 私の質問では目立つ省略を指摘してくれてありがとう。上記の編集を参照してください。問題が発生したときにデータベースに保存されます。 –
新しい 'ReportSection'を追加するときに' Claim'インスタンス全体の代わりに 'ClaimId'を提供してください:' r.ReportSections.Add(新しいReportSection {ClaimId = c.Id、Position = i}); ' – Diana