为什么在Entity Framework中忽略uint枚举

时间:2017-03-03 11:51:43

标签: c# .net entity-framework

好的,实体框架6.1.3,.Net Framework 4.5,这里是示例代码。

假设我有一个像这样的实体类:

public enum IdiocyLevel : uint { ExtremlyDumb, MaybeNotDumb, SmartEnough }
public enum SpreadLevel : byte { NoBodyUseIt, CommonUse, DeFactoStandart }

public class FrameworkReview
{
    public int Id { get; set; }
    public String FrameworkName { get; set; }
    public IdiocyLevel Idiocy { get; set; }
    public SpreadLevel Spread { get; set; }

    public override string ToString() { return String.Format("{0}:{1} - {2}, {3}", Id, FrameworkName, Spread, Idiocy); }
}

很简单。 Id键,字符串和两个枚举值。第一个枚举作为uint支持,第二个作为byte

我有一个DbContext类,如下所示:

public class DatabaseContext : DbContext
{
    public DbSet<FrameworkReview> Frameworks { get; set; }

    public DatabaseContext()
        : base("Data Source=(localdb)\\v11.0; Integrated Security=True; " +
               "AttachDbFilename=" + AppDomain.CurrentDomain.BaseDirectory + "enum.mdf")
    {
    }
}

现在,如果我使用这个类,我的第一个枚举总是存储为默认值:

class Program
{
    static void Main(string[] args)
    {
        FrameworkReview originalReview = new FrameworkReview()
        {
            FrameworkName = "EntityFramework",
            Idiocy = IdiocyLevel.SmartEnough,
            Spread = SpreadLevel.DeFactoStandart
        };
        Console.WriteLine(originalReview);

        int storedReviewId = 0;

        using (DatabaseContext dbContext = new DatabaseContext())
        {
            FrameworkReview storedReview = dbContext.Frameworks.Add(originalReview);
            dbContext.SaveChanges();

            Console.WriteLine(storedReview);
            storedReviewId = storedReview.Id;
        }

        using (DatabaseContext dbContext = new DatabaseContext())
        {
            FrameworkReview readedReview = dbContext.Frameworks.Find(storedReviewId);
            Console.WriteLine(readedReview);
        }

        Console.ReadKey(true);
    }
}

输出

0:EntityFramework - DeFactoStandart, SmartEnough
1:EntityFramework - DeFactoStandart, SmartEnough
1:EntityFramework - DeFactoStandart, ExtremlyDumb

为什么呢? EF不允许我存储uint值(这是C#枚举的默认值)?这是在文档中的某处说明的吗?

1 个答案:

答案 0 :(得分:4)

实体框架不支持无符号类型。

在这里阅读更多相关信息: How to use unsigned int / long types with Entity Framework?