Setting default value to enum property leads to getting that value assigned to that property after calling SaveChanges whether or not it's being set
When setting default value to enum in model through builder in OnModelCreating it appears that after adding newly created entity with that enum to dbContext and calling SaveChanges regardless to whether enum has been set in the process of entity creation the corresponding field of the entity is getting set to the default value.
Here is dotnetfiddle link for reproduction: https://dotnetfiddle.net/oR13Ox
Steps to reproduce
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
var orderType = OrderType.Sales;
var orderDate = new DateTime(2,2,2);
var order = new Order { Type = orderType, Date = orderDate };
context.Add(order);
context.SaveChanges();
Console.WriteLine($"Order type should be {orderType} but it's {order.Type}");
Console.WriteLine($"Order date should be {orderDate} and it's {order.Date}");
}
}
}
public class EntityContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
var connectionString = FiddleHelper.GetConnectionStringSqlServer();
//Console.WriteLine($"Configuring EntityContext with ad-hoc database from Fiddle: {connectionString}");
builder.UseSqlServer(new SqlConnection(connectionString))
.EnableDetailedErrors()
.EnableSensitiveDataLogging();
base.OnConfiguring(builder);
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder
.Entity<Order>()
.Property(o => o.Date)
.HasDefaultValue(new DateTime(3,3,3));
builder
.Entity<Order>()
.Property(o => o.Type)
.HasDefaultValue(OrderType.Purchase);
}
public DbSet<Order> Orders {get; set;}
}
public class Order
{
public int Id { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
public OrderType Type { get; set; }
}
public enum OrderType
{
Sales,
Purchase
}
Further technical details
EF Core version: 3.1.3 Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: .NET Core 3.1 Operating system: IDE: Visual Studio 2019 16.4.5
For some reason steps to reproduce section with the code doesn't appear, however I've added the code there, not sure what's the reason, but I also include dotnetfiddle link with code for reproduction
duplicate of #15070