EF Core 2.1.1 Seed method with consturctor call

asp.net-core c# entity-framework-core seeding

Question

Why property setted in constructor of seeding class is equal to 0? I have my own seed method:

    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 class have a constructor:

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;

}

That set value BaseSalary based on propertys from Seed like UsdPerHour, DaysOfWork etc.

From code above, my BaseSalary property in database is set to '0', all rows

My question is, is my methodCountBaseSalary from constructor get call when i starting Seeding my Data? Is it possible somehow run method CountBaseSalary after rows that are needed in this method? Where to cast my method to get value that i want to?

1
0
1/8/2019 4:42:30 PM

Accepted Answer

For Class, the Constructor is called before Properties initialize. So, you should avoid setting properties values from Constructor based on other properties.

Try

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);
}
1
1/9/2019 6:20:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow