'Database column defaults not behaving as expected
I have an issue where writing a new entry to the database isn't using the configured default values as I'd expect.
I have some classes:
public class Benefits
{
public string Id { get; set; }
[Required, ForeignKey("Id"), JsonIgnore]
public Employee Employee { get; set; }
[Column(TypeName = "money")]
public decimal BenefitsCost { get; set; }
[Column(TypeName = "decimal(16,8)"), DefaultValue(1)]
public decimal Modifier { get; set; }
}
public class BenefitsEmployee : Benefits
{}
public class BenefitsDependent : Benefits
{
[Required]
public string NameFirst { get; set; }
[Required]
public string NameLast { get; set; }
}
In OnModelCreating:
builder.Entity<BenefitsEmployee>().Property(b => b.BenefitsCost).HasDefaultValue(1000);
builder.Entity<BenefitsDependent>().Property(b => b.BenefitsCost).HasDefaultValue(500);
And, as last step in Configure, roughly:
var user = new {
Id = "SomeId",
NameFirst = "FirstName",
NameLast = "LastName",
SalaryBase = 0,
BenefitsCost = 0,
};
var emp = new Employee
{
Id = user.Id,
NameFirst = user.NameFirst,
NameLast = user.NameLast,
SalaryBase = user.SalaryBase,
BenefitsEmployee = new BenefitsEmployee
{
BenefitsCost = user.BenefitsCost,
},
};
await context.AddAsync(emp);
await context.SaveChangesAsync();
The problem is that BenefitsCost is set to 1000 and Modifier is set to 0 rather than 0 and 1 as I'd expect.
What might I be doing wrong?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
