0

我有 2 个表:一个 Orders 表和一个 OrderActivity 表。如果没有对订单进行任何活动,则 OrderActivity 表中将没有记录。我目前将 OrderActivity 表映射为 Order 实体上的可选导航属性,并且我处理对 OrderActivity 的更新,如下所示:

if (order.OrderActivity == null)
{
    order.OrderActivity = new OrderActivity();
}
order.OrderActivity.LastAccessDateTime = DateTime.Now;

是否可以合并它,以便 OrderActivity 表的列映射到 Orders 实体上的属性,并且如果没有 OrderActivity 记录将默认?仅当两个表中都存在记录时,实体拆分的配置才会起作用。如果不可能,从我的域模型中隐藏子实体的最佳做法是什么?我的目标是在与我无法控制的数据库模式交互时尽可能保持模型干净。

4

1 回答 1

0

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);
于 2013-05-22T03:11:56.680 回答