带有构造函数调用的EF Core 2.1.1种子方法

时间:2019-01-08 16:34:59

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

为什么在种子类的构造函数中设置的属性等于0?我有自己的种子方法:

    public static void Seed(this ModelBuilder modelBuilder)
    {
        Random random = new Random();
        int range = 20; // for doubles

        int countOfWorkers = 10;

        modelBuilder.Entity<Farm>().HasData(Farm.GetFarm());

        for (int i = 0; i < countOfWorkers; i++)
        {
            modelBuilder.Entity<Driver>().HasData(
            new Driver
            {
                // i belive that constructor launch in here
                Id = i + 1,
                FarmId = 1,
                FirstName = "name" + i,
                LastName = "lastname" + i,
                UsdPerHour = Math.Round((random.NextDouble() * 20), 2),
                HoursPerDay = random.Next(1, 23),
                DaysOfWork = random.Next(1, 31)
            });
        }
    }

Driver类具有构造函数:

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

    public override double BaseSalary { get; set; }

    //this propertys like UsdPerHours are in my abstract 'Worker' class
    public override double CountBaseSalary() => UsdPerHour* HoursPerDay *DaysOfWork;

}

该设置值BaseSalary基于Seed的属性,例如UsdPerHourDaysOfWork等。

从上面的代码中,我在数据库中的BaseSalary属性设置为'0',所有行

我的问题是,当我开始播种数据时,构造函数的方法CountBaseSalary是否会被调用?是否可以在此方法所需的行之后以某种方式运行方法CountBaseSalary?在哪里撒我的方法来获得我想要的价值?

1 个答案:

答案 0 :(得分:1)

对于ClassConstructorProperties initialize之前被调用。因此,应避免基于其他属性从Constructor设置属性值。

尝试

for (int i = 0; i < countOfWorkers; i++)
{
    var driver = new Driver
    {
        // i belive that constructor launch in here
        Id = i + 1,
        FirstName = "name" + i,
        LastName = "lastname" + i,
        UsdPerHour = Math.Round((random.NextDouble() * 20), 2),
        HoursPerDay = random.Next(1, 23),
        DaysOfWork = random.Next(1, 31)
    };
    driver.BaseSalary = driver.CountBaseSalary();
    modelBuilder.Entity<Driver>().HasData(driver);
}