EF Core Explicit Values Discover What Happen When You Specify Value
Explicit Values for Generated Properties
A property whose value is generated either by Entity Framework or the database when the entity is added or updated is known as generated property. In some cases, you might want to set an explicit value for a generated property, rather than having one generated.
Here is a simple model which contains a single Order
entity.
public class Order { public int OrderID { get; set; } public int CustomerID { get; set; } public int EmployeeID { get; set; } public DateTime OrderDate { get; set; } }
In the Order class, OrderDate
property needs to be configured to have default value generated by the database for new entities.
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>() .Property(b => b.OrderDate) .HasDefaultValueSql("CONVERT(date, GETDATE())"); }
Now everytime a new order is added to the database, the OrderDate property will be set to the CLR default value for DateTime
, but if you to set the explicit value of OrderDate for any particular order, let's say 20-Dec-2017.
using (var context = new MyContext()) { var list = context.Orders.ToList(); var orderDetails = context.OrderDetails.Include(o => o.Order).ToList(); var order1 = new Order() { CustomerID = 6, EmployeeID = 8 }; var order2 = new Order() { CustomerID = 10, EmployeeID = 1, OrderDate = new DateTime(2017, 12, 20) }; context.Orders.Add(order1); context.Orders.Add(order2); context.SaveChanges(); }
We have added two orders, one with default OrderDate value which will set by the database and the other order has explicit OrderDate value.
If you open the database, you will see that the database generated value for the first order and our explicit value was used for the second.
ZZZ Projects