[英]Can a foreign key column be an Enum in Entity Framework 6 code first?
我首先將 EF5 DB 轉換為 EF6 代碼。 在舊設置中,有一些 FK 是字節。 並在應用程序中映射到帶有下划線類型字節的枚舉。 這一直很有效。
首先轉到代碼和 EF6,我發現聲稱枚舉應該“正常工作”,實際上常規列似乎就是這種情況。 我可以從這里開始
public byte FavPersonality {get;set;}
對此:
public Personality FavPersonality {get;set;}
但是當涉及到也是外鍵的列時,我收到此錯誤:
System.ArgumentException : The ResultType of the specified expression is not
compatible with the required type. The expression ResultType is 'Edm.Byte'
but the required type is 'Model.Personality'.
這是不能先用 EF6 + Code 完成的事情嗎?
編輯:
枚舉定義為 :byte
我剛剛遇到了同樣的問題,我的枚舉是一個基本的數字枚舉,但這是按消息搜索的第一個結果。 我的主對象上有一個子類型,其中的值是一組固定的值。 但是,這些對象也有對象,因此我們可以針對它們編寫查詢。
public class Foo {
[Key]
public int Id { get; set; }
public BarEnum BarId { get; set; }
[ForeignKey(nameof(BarId))]
public Bar Bar { get; set; }
}
public class Bar {
[Key]
public int Id { get; set; }
}
public enum BarEnum {
Type1,
Type2
}
此配置給了我與此問題中描述的相同的錯誤消息:
指定表達式的 ResultType 與所需類型不兼容。 表達式 ResultType 是“BarEnum”,但所需的類型是“Edm.Int”。
解決方法很簡單:只需更改Bar
的 Id 以使用枚舉,一切正常。 這有一定道理,因為有一個更值可能int
之外還有一個BarEnum
。
public class Bar {
[Key]
public BarEnum Id { get; set; }
}
編輯- 根據@krillgars 的回答,在現代 EF 中最好只使用實際的枚舉類型作為主鍵(和引用的外鍵) - EF6 和 EfCore 可以很好地映射出來。
舊答案
我也得到了錯誤:
所述與resultType是
MyEnum
指定表達式是與所要求的類型“Edm.Int32”兼容。 參數名稱:keyValues[0]
使用枚舉映射時:
[Column("MyActualFKColumnId", TypeName = "int")]
public MyEnum MyEnum { get; set; }
// NB : Foreign Key refers to the C# Property, not the DB Field
[ForeignKey("MyEnum")]
public MyEntityReferencedByEnum MyEntityReferencedByEnum { get; set; }
但是,我能夠通過恢復原始整數外鍵 ( MyActualFKColumnId
)、刪除[Column]
和[ForeignKey]
屬性,然后向類添加[NotMapped]
屬性來解決上述問題:
[NotMapped]
public MyEnum MyEnum
{
get { return (MyEnum) MyActualFKColumnId; }
set { MyActualFKColumnId=(int)value; }
}
當 PK 與 FK 與子實體不匹配時,您可能會收到此錯誤。 例如,當使用列順序與 FK 不匹配的復合 PK 時。 像這樣:
class Foo
{
[Key, Column(Order=10)]
int Pk1 {get; set;}
[Key, Column(Order=20)]
short Pk2 {get; set;}
[ForeignKey("Pk2,Pk1")] // <== ORDER DOESN'T MATCH PK OF CHILD ENTITY
Foo Child {get;set;}
}
使用上面的代碼,EF 將嘗試將表Foos
與其自身連接,但使用縱橫交錯的列,因此它們的類型將不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.