我發現這樣做,它的工作原理,它只是不直接的Enum。您必須創建一個可以隱式映射來回映射的外觀類。它可以工作,但不像我希望的那樣順利。
http://daniel.wertheim.se/2010/06/09/dealing-with-enumerations-and-entity-framework-4-code-first/
public enum InterestTypes
{
[Description("Attraction - for sightseers and adventurers.")] Attraction = 1,
[Description("Event - fun for everyone (limited time).")] Event = 2,
[Description("Recreation - parks, hiking, movies...")] Recreation = 3,
[Description("Restaurant - good eats.")] Restaurant = 4
}
public class InterestType
{
private InterestType()
: this(default(InterestTypes))
{
}
public InterestType(int value)
{
Value = value;
}
public InterestType(InterestTypes type)
{
Value = (int) type;
}
public int Value { get; private set; }
public static implicit operator int(InterestType type)
{
return type.Value;
}
public static implicit operator InterestType(int value)
{
return new InterestType(value);
}
public static implicit operator InterestTypes(InterestType type)
{
return (InterestTypes) type.Value;
}
public static implicit operator InterestType(InterestTypes type)
{
return new InterestType(type);
}
}
在你的DataContext你需要在OnModelCreating方法如下。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<InterestType>()
.Property(o => o.Value)
.HasColumnName("Type");
}
這告訴實體框架將int值映射到數據庫中的值。我想你也可以使用字符串,如果你想將值作爲字符串存儲在數據庫中。
可能重複的[如何在實體框架中使用Enums?](http://stackoverflow.com/questions/1526339/how-to-work-with-enums-in-entity-framework) – 2011-05-20 14:49:37
如某些陳述這不是EF的支持功能,請轉到http://data.uservoice.com/forums/72027-wcf-data-services-feature-suggestions/suggestions/1012609-support-enums-as-property-types- on-entities?ref =標題和投票將包含在將來的版本 – 2011-05-20 14:57:07