身份为0的实体框架核心种子数据

时间:2019-01-16 20:01:50

标签: asp.net-core ef-core-2.1

我正在尝试使用.HasData向我的模型中添加一些种子数据,以便填充数据库。我在数据模型中使用ID 0来映射到每个表上的未知数。

添加此代码后尝试运行应用程序时,出现以下错误:

  

无法添加实体类型“ DboTable”的种子实体,因为   没有为必填属性“ Id”提供任何值。

我假设EFCore强制使用null值,因为整数0等于null,但是当我尝试强制执行整数解析时,它仍然会引发相同的错误。

目前我不确定如何处理此问题,任何建议都将不胜感激。

DbContext.cs中的代码段

...
entity.HasData(new DboTable()
{
    Id = 0,               // integer
    Label = "UNKNOWN",    // string
    ...
});
...

2 个答案:

答案 0 :(得分:0)

事实证明EF Core 2.1不支持PK值0。

不幸的是,任何试图为PK使用0值的种子数据都必须使用自定义SQL进行迁移,以插入其PK 0记录。

请参阅:https://github.com/aspnet/EntityFrameworkCore/issues/12399

答案 1 :(得分:0)

在对EF Core代码进行反向工程并找到了this行代码之后,我创建了一些小的“ hack”来绕过0 PK值限制

这是我的扩展名代码:

using System;
using System.Linq;
using System.Collections.Generic;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace EntityFrameworkCore.CustomMigration
{
    public static class CustomModelBuilder
    {
        public static bool IsSignedInteger(this Type type)
           => type == typeof(int)
              || type == typeof(long)
              || type == typeof(short)
              || type == typeof(sbyte);

        public static void Seed<T>(this ModelBuilder modelBuilder, IEnumerable<T> data) where T : class
        {
            var entnty = modelBuilder.Entity<T>();

            var pk = entnty.Metadata
                .GetProperties()
                .FirstOrDefault(property => 
                    property.RequiresValueGenerator() 
                    && property.IsPrimaryKey()
                    && property.ClrType.IsSignedInteger()
                    && property.ClrType.IsDefaultValue(0)
                );
            if (pk != null)
            {
                entnty.Property(pk.Name).ValueGeneratedNever();
                entnty.HasData(data);
                entnty.Property(pk.Name).UseSqlServerIdentityColumn();
            }
            else
            {
                entnty.HasData(data);
            }          
        }
    }
}

您可以在OnModelCreating方法中像这样使用它:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Seed(new List<Tenant> {
        new Tenant() {TenantID = 0 , Name = string.Empty},
        new Tenant() {TenantID = 1 , Name = "test"}
        //....
        );

    //....
}
相关问题