为什么在种子类的构造函数中设置的属性等于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的属性,例如UsdPerHour
,DaysOfWork
等。
从上面的代码中,我在数据库中的BaseSalary
属性设置为'0',所有行
我的问题是,当我开始播种数据时,构造函数的方法CountBaseSalary
是否会被调用?是否可以在此方法所需的行之后以某种方式运行方法CountBaseSalary
?在哪里撒我的方法来获得我想要的价值?
答案 0 :(得分:1)
对于Class
,Constructor
在Properties 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);
}