You can create the mapping and specify the type of LastAccessDate
as Nullable<DateTime>
. The mapping will create one-to-one with LastAccessDate
being optional.
public class Order {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime? LastAccessDate { get; set; }
}
modelBuilder.Entity<Order>().Map(m => {
m.Properties(a => new { a.Id, a.Name });
m.ToTable("Order");
}).Map(m => {
m.Properties(b => new { b.Id, b.LastAccessDate });
m.ToTable("OrderActivity");
});
In this case, specifying LastAccessDate
property is optional when inserting new orders.
var order = new Order();
order.Name = "OrderWithActivity";
order.LastAccessDate = DateTime.Now;
db.Orders.Add(order);
db.SaveChanges();
order = new Order();
order.Name = "OrderWithoutActivity";
db.Orders.Add(order);
db.SaveChanges();
Note this will always create one entry in each table. This is necessary because EF creates INNER JOIN
when you retrieve Orders and you want to get all orders in this case. LastAccessDate
will either have a value or be null.
// Gets both orders
var order = db.Orders.ToList();
// Gets only the one with activity
var orders = db.Orders.Where(o => o.LastAccessDate != null);