日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

EF学习杂记39:如何重置Relationships

發布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 EF学习杂记39:如何重置Relationships 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景:

在EF4.0中引入了FK relationships的概念,所以現在可以建立這樣的一種模型:

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;}
}

注意,這里Lawyer擁有組合主鍵LawyerID 和DivisionID。

Notice that the Lawyer has a Compound key made up of both the LawyerID and DivisionID.

當你在創建包含組合式外鍵Lawyer和Division的類ProductTeam的時候,事情講變得有趣,如果你象下面這樣操作:

var team = (from t in ctx.ProductTeams
????????????????? where t.Lawyer.Name == “Fred Bloggs”
????????????????? select t).FirstOrDefault();
team.Lawyer = null;
ctx.SaveChanges();

這里EF的真實操作是怎樣的呢?

為了清除這個Relationship,這里到底是同時清除外鍵team.LawyerIDteam.DivisionID呢還是僅僅清除外鍵team.LawyerID?

Does this mean clear team.LawyerID & team.DivisionID or just team.LawyerID?

從Relationship的角度來看,只要清除任何一個可空的外鍵就可以使這個Relationship被清除。

這里很難說用戶傾向哪一種,與其介紹一些特殊的規定,我們還是來看看EF所使用的限制和規則,我們可以遵守:

當用戶需要把一個Relationship設置成空的時候,EF將把所有可空的外鍵設置為空,無論該外鍵屬性是否參與了其他Relationship。

問題:

根據上面的規則,這里EF是同時把DivisionID 和LawyerID兩個外鍵屬性都置空了,因為它們都返回到了Lawyer的導航屬性中。

上面的方式將同時把LawyerDivision兩個對象同時置空,你真的想那樣嗎,或許不是。

解決辦法:

如果你只是想置空Lawyer,你有兩種選擇:

選擇一:改變模型中外鍵DivisionID的可空屬性,在這里EF僅可以使LawyerID可空,這樣Relationshiip將可以完整保留。但這種解決方案需要改變模型,這個并不是總是可以的,如果Division確實需要可空呢?

更好的辦法是直接操縱未見屬性:

var team = (from t in ctx.ProductTeams
????????????????? where t.Lawyer.Name == “Fred Bloggs”
????????????????? select t).FirstOrDefault();
team.LawyerID = null;
ctx.SaveChanges();

這樣的方式僅僅涉及到了Lawyer,不會對Division造成影響。

轉載于:https://www.cnblogs.com/brusehht/archive/2010/09/01/1815077.html

總結

以上是生活随笔為你收集整理的EF学习杂记39:如何重置Relationships的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。