Wil*_*ler 2 enums attributes persistence wrapper entity-framework-4
我有一个枚举,我希望将其作为某种值保存到底层数据库中,以便我可以来回传递它.
我已经阅读了一些建议创建枚举包装器的文章,其中定义了静态隐式运算符,使用ComplexType对象映射进行映射,如下面的链接所述.
这个解决方案完美无瑕!我要感谢Alex James.
除此之外,我发现了EnumDataTypeAttribute Class哪个目的似乎通过实体框架处理枚举持久性.我试了一下它似乎根本没用.这是一个代码示例.
public enum StreetDirection {
East
, None
, North
, NorthEast
, NorthWest
, South
, SouthEast
, SouthWest
, West
}
public enum StreetType {
Avenue
, Boulevard
, Court
, Crescent
, Drive
, Hill
, None
, Road
, Street
}
public class StreetTypeWrapper {
public int Value {
get {
return (int)t;
}
set {
t = (StreetType)value;
}
}
public StreetType EnumValue {
get {
return t;
}
set {
t = value;
}
}
public static implicit operator int(StreetTypeWrapper w) {
return w.Value;
}
public static implicit operator StreetType(StreetTypeWrapper w) {
return w == null ? StreetType.None : w.EnumValue;
}
public static implicit operator StreetTypeWrapper(int i) {
return new StreetTypeWrapper() { Value = i };
}
public static implicit operator StreetTypeWrapper(StreetType t) {
return new StreetTypeWrapper() { EnumValue = t };
}
private StreetType t;
}
public class Street {
[EnumDataType(typeof(StreetDirection))]
public StreetDirection Direction { get; set; }
public string Name { get; set; }
public int StreetId { get; set; }
public StreetTypeWrapper Type { get; set; }
}
public class StreetTypeMapping
: ComplexTypeConfiguration<StreetTypeWrapper> {
public StreetTypeMapping() {
Property(o => o.Value)
.HasColumnName("StreetType");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我相信和/或正确理解MSDN对该EnumDataTypeAttribute类的描述,该Direction属性应该持久存储到数据库中.好吧,它没有!除了EF不支持枚举持久性之外,我找不到合理的理由.至于它StreetTypeWrapper和它的StreetTypeMapping类,它确实完美地工作.
是否有任何线索为什么EnumDataType不能按预期工作?
Lad*_*nka 10
这是因为.NET框架中的设计缺陷..NET框架包含System.ComponentModel.DataAnnotations名称命名空间,其中定义了多个不同的属性 .NET框架的许多不同部分都使用此命名空间,但它们使用它来实现不同的任务,并且每个这样的部分仅使用某些属性子集.这引起了很多困惑.
EnumDataTypeAttribute就是这样的例子.此属性仅适用于ASP.NET动态数据.它允许您使用此属性标记int属性,并且自动生成的UI将显示下拉列表,其中包含枚举值而不是文本框中的数值.因此存在从枚举到int的映射,但它在UI层中而不是在模型/持久层中.