最近我又回到了企业应用程序的 NHibernate 与 EF5 的问题。我知道许多重要的区别,但这个对我来说是最令人惊讶的。考虑两个经典实体 Customer 和 Order (1:n):
public class Customer
{
public Customer()
{
Orders = new HashSet<Order>();
}
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
**public virtual ICollection<Order> Orders { get; set; }**
}
public class Order
{
public virtual Guid Id { get; set; }
public virtual Guid CustomerId { get; set; }
public virtual string Number { get; set; }
public virtual DateTime Date { get; set; }
**public virtual Customer Customer { get; set; }**
}
NHibernate 和 EF5 都有双向映射。相应地在 DbContext 和 Session 的上下文中加载所有客户和所有订单的代码片段,用于 EF5 和 NHibernate:
using (TestOrmForDalDbEntities context = new TestOrmForDalDbEntities())
{
context.Configuration.ProxyCreationEnabled = false;
IQueryable<Customer> customers = context.Customers;
customers.Load();
IQueryable<Order> orders = context.Orders;
orders.Load();
}
using (ISession session = _sessionFactory.OpenSession())
{
var customers = session.Query<Customer>().ToList();
var orders = session.Query<Order>().ToList();
}
结果是:
EF5:每个客户都有一组适当的订单(EF5 自动连接它们) NHibernate:没有一个客户有一组适当的订单。即使每个订单都链接到适当的客户。
问题是:不以这种方式连接是 NHibernate 的想法还是我不知道如何配置 NHibernate?
NHibernate 的 PS 映射:
public class CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
Id(x => x.Id).UnsavedValue(Guid.Empty).GeneratedBy.Guid();
Map(x => x.Name);
HasMany(x => x.Orders).Cascade.All();
}
}
public OrderMap()
{
Id(x => x.Id).UnsavedValue(Guid.Empty).GeneratedBy.Guid();
Map(x => x.Number);
Map(x => x.Date);
Map(x => x.CustomerId);
References(x => x.Customer);
}