EF Core 2.1.1种子数据无法与替代double一起使用

时间:2019-01-08 15:00:16

标签: c# asp.net-core entity-framework-core seeding

您能告诉我为什么在我的数据库中,在0之后获得Seed method的值吗?看起来像这样:

public static void Seed(this ModelBuilder modelBuilder)
    {
        int countOfWorkers = 10;

        for (int i = 0; i < countOfWorkers; i++)
        {
            modelBuilder.Entity<Driver>().HasData(
            new Driver
            {
                // 10 same workers
                Id = i + 1,
                FarmId = 1,
                FirstName = "name" + i,
                LastName = "lastname" + i,
                UsdPerHour = 7.2,
                HoursPerDay = 8,
                DaysOfWork = 31
            });
        }
    }

还有我的Models类:

public abstract class Worker
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Farm")]
    public int FarmId { get; set; }
    public Farm Farm { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual double UsdPerHour { get; set; }
    public virtual int HoursPerDay { get; set; }
    public virtual int DaysOfWork { get; set; }

    public virtual double CountBaseSalary() => throw new NotImplementedException();
}

public class Driver : Worker
{
    public Driver() => BaseSalary = CountBaseSalary();

    public override double UsdPerHour { get; set; }
    public override int HoursPerDay { get; set; }
    public override int DaysOfWork { get; set; }

    public override double CountBaseSalary() => UsdPerHour* HoursPerDay *DaysOfWork;

}

我正在使用EF Core 2.1.1。我做错了什么,我获得了0's值的Driver属性?如果需要,我可以添加更多信息。

我的DbContext

public class FarmDbContext : DbContext
{
    public FarmDbContext(DbContextOptions<FarmDbContext> options) : base(options) { }

    public DbSet<Farm> Farms { get; set; }
    public DbSet<Worker> Workers { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Driver>();
        builder.Seed();
        base.OnModelCreating(builder);
    }
}

1 个答案:

答案 0 :(得分:1)

如果所有Worker都具有UsdPerHour, HoursPerDay, DaysOfWork,则您不需要Driver中指定的那些字段,它们将被继承。

如果只有Driver需要这些字段,则应将它们从基类Worker中删除。