のために外部キープロパティを公開しないエンティティの保存中にエラーが発生しました(私は関連の質問をチェックしました、と答えを見つけることができません。)省関連企業 - 彼らの関係
アイムCode First Entity Framework 6でいくつかのテストを行っています。 私は2つの "親"エンティティを参照する "子"エンティティを持っています。
子エンティティと親エンティティを作成して一度に保存したいので、db.Save()コールの数を減らし、1つの作業単位として保持してください。
public class Child
{
public int ChildID { get; set; }
public string Name { get; set; }
public virtual Parent Father { get; set; }
public virtual Parent Mother { get; set; }
}
public class Parent
{
public int ParentID { get; set; }
public string Name { get; set; }
[ForeignKey("Child")]
public int? ChildID { get; set; }
public virtual Child Child { get; set; }
}
(紛らわしいセットアップのビット - 両親は、実際の関係で子供の「子」です私はこれは単なるテストである、それは悪い抽象化であることを知っている。。。)
コントローラ:
public ActionResult AddWithParents()
{
Parent father = new Parent { Name = "Test Father" };
Parent mother = new Parent { Name = "Test Mother" };
Child newChild = new Child
{
Name = "Test Child",
Father = father,
Mother = mother
};
db.Children.Add(newChild);
father.Child = newChild;
mother.Child = newChild;
db.SaveChanges();
return RedirectToAction("Index");
}
これは機能しますが、Parent.ChildID外部キーには入力されません。
私はfather.Child =にnewChildような何かをした場合、私は次のエラーを取得する:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details. Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
は、この作業を取得する方法はありますか?
あなたの内側の例外は何ですか? 'SqlException'が表示されている場合は、存在する場合はnullまたは範囲外の値に対して日時データ型をチェックします。 –
モデルにはデータがありません。 誰かが私の質問を再フォーマットして内部例外が主要な例外の一部であるが、内部例外は 従属操作の有効な順序を判断できません。依存関係は、外部キー制約、モデル要件、またはストア生成値のために存在する可能性があります。 – mcfroob
まあ、内部例外は、EFが主キーの値がnullまたは無効なエンティティを見つけようとする循環依存の問題があることを伝えます。外部キーにnullable型があるかどうかを確認するか、関連するテーブル間の関係を調べます。それでは、どんなタイプの関係を作りたいですか(1:1、1:n)? –