[英]EntityFramework Code First 1 to 1 data add
我正在使用代碼優先的方式創建數據庫。 我有兩個1對1關系的實體,但我真的不知道如何實例化它們。
假設這些是我的實體:
public class Foo
{
[Key]
public int Id {get;set;}
[ForeignKey("BigFoo")]
public int BigFooId {get;set;}
public virtual BigFoo BigFoo {get;set;}
}
public class BigFoo
{
[Key]
public int Id {get;set;}
[ForeignKey("Foo")]
public int FooId{get;set;}
public virtual Foo Foo {get;set;}
}
這是我的代碼:
Foo foo = new Foo();
foo = db.Foo.Add(foo);
BigFoo big = new BigFoo {Foo = foo, FooId = foo.Id};
big = db.BigFoo.Add(big);
//HERE is my doubt
//I don't know if I have to add the relation also in the Foo object
//Do i need the following code?
//foo.BigFoo = big;
//foo.BigFooId = big.Id;
//db.Foo.Attach(foo);
//var entry = db.Entry(foo);
//entry.Property(x => x.BigFoo).IsModified = true;
db.SaveChanges();
該關系已在我的BigFoo對象聲明中設置,我是否還需要在Foo對象中設置此關系,否則它將自動分配?
謝謝大家的幫助。
編輯:
我有另一個疑問:我的外鍵名為relateddentityIdField。
我必須和他們一起解決這個問題
foo.BigFooId = big.Id;
或者那些關系是自動填充的?
添加示例 - 編輯
一個例子可以是國家 - 總統的關系
每個國家只有一位總統,每位總統都只是一個國家的總統。
如何使用Code-First設置此關系?
使用當前模型,您真正擁有的是兩個一對多的單向關系。 要使用Code First創建一對一關系,您必須將依賴實體的PK定義為關系的FK(請查看此鏈接以獲取詳細說明)。
public class Foo
{
public int Id{get;set;}
public virtual Boo Boo {get;set;}
}
public class Boo
{
[Key, ForeignKey("Foo")]
public int FooId{get;set;}
public virtual Foo Foo {get;set;}
}
使用此模型,您可以按如下方式添加數據:
如果要創建新的Foo
和Boo
並且想要關聯它們,可以執行以下操作:
var boo=new Boo(); var foo=new Foo{Boo=boo }; context.Foos.Add(foo); context.SaveChanges();
您應該看到Boo
實體中的Foo
導航屬性也已填充。
如果Foo
已經存在並且你想創建一個與該foo相關的新Boo
:
您可以在foo實體中設置Boo
導航屬性:
var foo= context.Find(yourId); foo.Boo=new Boo(); context.SaveChanges();
或者您可以設置新Boo
實體的PK / FK屬性:
var fooId=1;// You already have the Foo id var boo = new Boo() { FooId = fooId}; context.Boos.Add(boo); context.SaveChanges();
如前所述,使你的模型發白,你有兩種不同的關系,所以你的導航屬性並不真正相關。 如果您想證明這一點,請向您的實體添加兩個集合:
public class Foo
{
[Key]
public int Id {get;set;}
[ForeignKey("BigFoo")]
public int? BigFooId {get;set;}
public virtual BigFoo BigFoo {get;set;}
public virtual ICollection<BigFoo> BigFoo{get;set;}// Add this property
}
public class BigFoo
{
[Key]
public int Id {get;set;}
[ForeignKey("Foo")]
public int? FooId { get; set; }
public virtual Foo Foo {get;set;}
public virtual ICollection<Foo> Foos{get;set;}// Add this property
}
然后嘗試這個:
using (var context=new MyContext())
{
var foo = new Foo();
context.Foos.Add(foo);
context.SaveChanges();
var boo = new BigFoo() { FooId = foo.Id};
context.Boos.Add(boo);
context.SaveChanges();
}
在最后的SaveChanges
之后,你將Foo
導航。 boo
實例中的屬性和foo
實例中的BigFoos
nav屬性已正確填充。
注意:我將導航屬性更改為virtual
以滿足延遲加載的要求之一,並且還將您的FK屬性更改為nullables以避免級聯刪除循環。 Code First沒有為可選關系設置級聯刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.