如何在EF Core Code First中创建与枚举相对应的表?

时间:2018-05-16 15:59:38

标签: c# enums entity-framework-core

如何将EF Core数据库上下文中使用的枚举转换为查找表并添加相关的外键?

1 个答案:

答案 0 :(得分:5)

通过结合使用以下两个EF Core功能,您可以在代码中使用枚举并在数据库中具有查找表:


下面是一个数据模型示例:

public class Wine
{
    public int WineId { get; set; }
    public string Name { get; set; }

    public WineVariantId WineVariantId { get; set; }
    public WineVariant WineVariant { get; set; }
}

public enum WineVariantId : int
{
    Red = 0,
    White = 1,
    Rose = 2
}

public class WineVariant
{
    public WineVariantId WineVariantId { get; set; }
    public string Name { get; set; }

    public List<Wine> Wines { get; set; }
}

DbContext中,您可以配置值转换和数据种子:

public class WineContext : DbContext
{
    public DbSet<Wine> Wines { get; set; }
    public DbSet<WineVariant> WineVariants { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=wines.db");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Wine>()
            .Property(e => e.WineVariantId)
            .HasConversion<int>();

        modelBuilder
            .Entity<WineVariant>()
            .Property(e => e.WineVariantId)
            .HasConversion<int>();

        modelBuilder
            .Entity<WineVariant>().HasData(
                Enum.GetValues(typeof(WineVariantId))
                    .Cast<WineVariantId>()
                    .Select(e => new WineVariant()
                    {
                        WineVariantId = e,
                        Name = e.ToString()
                    })
            );
    }
}

然后,您可以在代码中使用枚举值,如下所示:

db.Wines.Add(new Wine
{
    Name = "Gutturnio",
    WineVariantId = WineVariantId.Red,
});

db.Wines.Add(new Wine
{
    Name = "Ortrugo",
    WineVariantId = WineVariantId.White,
});

这是您的数据库将包含的内容:

WineVariants table

Wines table

我以要点发布了完整的示例:https://gist.github.com/paolofulgoni/825bef5cd6cd92c4f9bbf33f603af4ff