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

查看:483
本文介绍了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. 如何使用流利的api配置它?

谢谢

编辑:

枚举:

  public enum LimitMode 
    {
        Max,
        Min,
        MaxAndMin,
    }

型号:

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

SomeModel的ModelBuilder:

ModelBuilder for SomeModel:

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


推荐答案

值转换器现在已在EntityFrameworkCore 2.1中受支持。
这使您可以将枚举视为数据库中的字符串,并将其正确转换为模型中的枚举。

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天全站免登陆