EF学习杂记39:如何重置Relationships
場(chǎng)景:
在EF4.0中引入了FK relationships的概念,所以現(xiàn)在可以建立這樣的一種模型:
public class Division
{
?? public int DivisionID {get;set} // Primary Key
?? public string Name {get;set;}
?? public virtual List<Lawyer> Lawyers {get;set;}
?? public virtual List<Unit> Units {get;set;}
}
public class Lawyer
{
?? public int LawyerID {get;set;} // Primary Key
?? public int DivisionID {get;set;} // Primary Key + FK to Division
?? public string Name {get;set;}
?? public virtual Division Division {get;set;}
?? public virtual List<Unit> Units {get;set;}
}
public class ProductTeam
{
??? public int ProductID {get;set;} // Primary Key
??? public int? DivisionID {get;set;} // FK to Division & Lawyer
??? public int? LawyerID {get;set;} // FK to Lawyer
??? public string Name {get;set;}
??? public virtual Division Division {get;set;}
??? public virtual Lawyer Lawyer {get;set;}
}
注意,這里L(fēng)awyer擁有組合主鍵LawyerID 和DivisionID。
Notice that the Lawyer has a Compound key made up of both the LawyerID and DivisionID.
當(dāng)你在創(chuàng)建包含組合式外鍵Lawyer和Division的類ProductTeam的時(shí)候,事情講變得有趣,如果你象下面這樣操作:
var team = (from t in ctx.ProductTeams
????????????????? where t.Lawyer.Name == “Fred Bloggs”
????????????????? select t).FirstOrDefault();
team.Lawyer = null;
ctx.SaveChanges();
這里EF的真實(shí)操作是怎樣的呢?
為了清除這個(gè)Relationship,這里到底是同時(shí)清除外鍵team.LawyerID和team.DivisionID呢還是僅僅清除外鍵team.LawyerID?
Does this mean clear team.LawyerID & team.DivisionID or just team.LawyerID?
從Relationship的角度來(lái)看,只要清除任何一個(gè)可空的外鍵就可以使這個(gè)Relationship被清除。
這里很難說(shuō)用戶傾向哪一種,與其介紹一些特殊的規(guī)定,我們還是來(lái)看看EF所使用的限制和規(guī)則,我們可以遵守:
當(dāng)用戶需要把一個(gè)Relationship設(shè)置成空的時(shí)候,EF將把所有可空的外鍵設(shè)置為空,無(wú)論該外鍵屬性是否參與了其他Relationship。
問(wèn)題:
根據(jù)上面的規(guī)則,這里EF是同時(shí)把DivisionID 和LawyerID兩個(gè)外鍵屬性都置空了,因?yàn)樗鼈兌挤祷氐搅薒awyer的導(dǎo)航屬性中。
上面的方式將同時(shí)把Lawyer和Division兩個(gè)對(duì)象同時(shí)置空,你真的想那樣嗎,或許不是。
解決辦法:
如果你只是想置空Lawyer,你有兩種選擇:
選擇一:改變模型中外鍵DivisionID的可空屬性,在這里EF僅可以使LawyerID可空,這樣Relationshiip將可以完整保留。但這種解決方案需要改變模型,這個(gè)并不是總是可以的,如果Division確實(shí)需要可空呢?
更好的辦法是直接操縱未見(jiàn)屬性:
var team = (from t in ctx.ProductTeams
????????????????? where t.Lawyer.Name == “Fred Bloggs”
????????????????? select t).FirstOrDefault();
team.LawyerID = null;
ctx.SaveChanges();
這樣的方式僅僅涉及到了Lawyer,不會(huì)對(duì)Division造成影響。
轉(zhuǎn)載于:https://www.cnblogs.com/brusehht/archive/2010/09/01/1815077.html
總結(jié)
以上是生活随笔為你收集整理的EF学习杂记39:如何重置Relationships的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring PropertyPlace
- 下一篇: IE6使用png透明图片的方法