[英]Linq-To-SQL Association with Multiple Foreign Keys Problem
我正在使用Visual Studio 2008,C#,LINQ to SQL,並使用datbase dbml GUI編輯器來創建數據庫。 我想創建1對多關系,但是在我的情況下1對象具有2個主鍵。 使用GUI edtior創建了關聯,但是當程序運行並創建數據庫時,出現錯誤:
“引用的表必須具有主鍵或候選鍵。[FK名稱= Screen_Pixel]”
在dbml中創建的XML看起來像:
<Table Name="Screen">
<Column Name="PKA1" Type="System.Int64" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Column Name="PKA2" Type="System.Int32" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Association Name="Screen_Pixel" Member="Pixels" ThisKey="PKA1,PKA2" OtherKey="PKB1,PKB2" Type="Pixel" />
</Table>
<Table Name="Pixel>
<Column Name="PKB1" Type="System.Int64" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Column Name="PKB2" Type="System.Int32" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Column Name="PKB3" Type="System.Int32" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Association Name="Screen_Pixel" Member="Screen" ThisKey="PKB1,PKB2" OtherKey="PKA1,PKA2" Type="Screen" IsForeignKey="true" />
</Table>
用C#代碼生成的關聯為:
[Association(Name=@"Screen_Pixel", Storage=@"_Screen", ThisKey=@"PKA1,PKA2", OtherKey=@"PKB1,PKB2", IsForeignKey=true)]
[Association(Name=@"Screen_Pixel", Storage=@"_Pixels", ThisKey=@"PKB1,PKB2", OtherKey=@"PKA1,PKA2")]
有任何想法嗎?
由於我一直在努力解決類似問題,並且這個問題接近我的問題,因此我將在這里添加2美分,以解決下一個可能因同一問題而產生的靈魂(在運行時從對象模型創建數據庫)。
如果您的組合鍵實際上不必一定是主鍵(例如,您只想提供組合的唯一性),則解決方案是:
提供唯一性約束,並在DataContext上增加一個步驟,例如:
yourDataContext.ExecuteCommand("ALTER TABLE Stuff ADD UNIQUE (unique_thing_1, unique_thing_2, unique_thihng_3)");
之后,嘗試插入重復的字段時,提交將引發異常。
為什么要使用多個字段作為主字段(也稱為“復合主字段”)?
一些學校和書籍教導使用“復合主鍵”,但是實際上,這不是一個好主意。 許多軟件不允許這些字段,即使允許,也很難處理。
最好使用單個字段的主鍵。
我的建議是將這些字段保留為標准字段或外鍵,並添加一個自動分配或遞增的新字段 。
例:
<Table Name="Screen"> <Column Name="ScreenKey" Type="System.Int64" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Column Name="ScreenField1" Type="System.Int64" IsPrimaryKey="false" CanBeNull="false" UpdateCheck="Never" />
<Column Name="ScreenField2" Type="System.Int32" IsPrimaryKey="false" CanBeNull="false" UpdateCheck="Never" />
<Association Name="Screen_Pixel" Member="Pixels" ThisKey="ScreenKey" OtherKey="ScreenKey" Type="Pixel" />
</Table>
<Table Name="Pixel>
<Column Name="PixelKey" Type="System.Int64" IsPrimaryKey="true" CanBeNull="false" UpdateCheck="Never" />
<Column Name="ScreenKey" Type="System.Int64" IsPrimaryKey="false" CanBeNull="false" UpdateCheck="Never" />
<Column Name="PixelField1" Type="System.Int64" IsPrimaryKey="false" CanBeNull="false" UpdateCheck="Never" />
<Column Name="PixelField2" Type="System.Int32" IsPrimaryKey="false" CanBeNull="false" UpdateCheck="Never" />
<Column Name="PixelField3" Type="System.Int32" IsPrimaryKey="false" CanBeNull="false" UpdateCheck="Never" />
<Association Name="Screen_Pixel" Member="Screen" ThisKey="ScreenKey" OtherKey="ScreenKey" Type="Screen" IsForeignKey="true" />
</Table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.