EF7 (EFCore) 是否支持枚举? [英] Does EF7 (EFCore) support enums?

查看:18
本文介绍了EF7 (EFCore) 是否支持枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 EF7 RC1 (EFCore) 有问题.我无法在我的模型中使用枚举.我可以保存枚举属性.该值被强制转换为 int.我的问题是在数据读取过程中我得到了无效的强制转换异常.

I have problem with EF7 RC1 (EFCore). I am unable to work with enums in my model. I can save enum property. The value is casted to int. My problem is that during data reading i get invalid cast exception.

  1. EF7 是否支持枚举属性?
  2. 如何使用 fluent api 配置它?

谢谢

枚举:

  public enum LimitMode 
    {
        Max,
        Min,
        MaxAndMin,
    }

型号:

  public class SomeModel 
    {
    (..)
    public LimitMode LimitMode {get; set;}
    }

用于 SomeModel 的模型构建器:

ModelBuilder for SomeModel:

        modelBuilder.Entity<SomeModel>(entity => {
            (...)
            entity.Property(p => p.LimitMode);
        })

推荐答案

EntityFrameworkCore 2.1 现在支持值转换器这允许您将 Enum 视为数据库中的字符串,并让它们在模型中正确转换为 Enum.

Value converters are now supported in EntityFrameworkCore 2.1 This allows you to treat Enums as strings in your database and have them correctly convert to Enums in your model.

您可以使用值转换器执行此操作.您可以创建自己的,但 EF Core 2.1 附带了一些开箱即用的预定义值转换器.其中之一是 EnumToString 值转换器.

You do this with a value converter. You can create your own but EF Core 2.1 comes with some pre-defined value converters out of the box. One of these is the EnumToString value converter.

因此给出以下内容:

public class Rider
{
    public int Id { get; set; }
    public EquineBeast Mount { get; set; }
}

public enum EquineBeast
{
    Donkey,
    Mule,
    Horse,
    Unicorn
}

像这样使用默认转换器:

Use the default converter like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Rider>()
        .Property(e => e.Mount)
        .HasConversion<string>();
}

或者,如果您更喜欢在模型类上使用这样的属性:

Or if you prefer using attributes on your model classes like this:

public class Rider
{
    public int Id { get; set; }

    [Column(TypeName = "nvarchar(24)")]
    public EquineBeast Mount { get; set; }
}

这篇关于EF7 (EFCore) 是否支持枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆