use*_*503 11 c# enums foreign-keys entity-framework-6
我首先将EF5 DB转换为EF6代码.在旧的设置中有一些字节的FK.并在应用程序中映射到具有下划线类型的字节的枚举.这一直很有效.
首先转到代码和EF6我发现枚举应该"正常工作",事实上这似乎是常规列的情况.我可以从这里走出来
public byte FavPersonality {get;set;}
Run Code Online (Sandbox Code Playgroud)
对此:
public Personality FavPersonality {get;set;}
Run Code Online (Sandbox Code Playgroud)
但是当涉及到也是外键的列时,我收到此错误:
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'.
Run Code Online (Sandbox Code Playgroud)
这是先用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
}
Run Code Online (Sandbox Code Playgroud)
此配置给了我与此问题中描述的相同的错误消息:
指定表达式的ResultType与所需类型不兼容.表达式ResultType为'BarEnum',但所需类型为'Edm.Int'.
对此的解决方法很简单:只需更改Id Bar以使用枚举,一切都可以正常工作.这确实有意义,因为a的可能值远远int超过a BarEnum.
public class Bar {
[Key]
public BarEnum Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Edit - As per @krillgars answer, in modern EF it's better to just use the actual enum type as the Primary Key (and referenced Foreign Keys) - EF6 and EfCore can map this out fine.
Old Answer
I also got the error:
The ResultType is
MyEnumof the specified expression is not compatible with the required type 'Edm.Int32'. Parameter name: 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; }
Run Code Online (Sandbox Code Playgroud)
但是,我可以通过恢复原始整数外键 ( MyActualFKColumnId)、删除[Column]和[ForeignKey]属性,然后[NotMapped]向类添加属性 hack 来解决上述问题:
[NotMapped]
public MyEnum MyEnum
{
get { return (MyEnum) MyActualFKColumnId; }
set { MyActualFKColumnId=(int)value; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3286 次 |
| 最近记录: |