开发者

NHibernate uni-directional associations

Playing around with Fluent NHibernate's Getting Started project. I tried to customize the example a bit, for a few reasons, among them elimination of circular reference for json serialization.

What I have done is to strip the Store and StoreMap classes of it's references back to Employee and Product classes. It now looks like this:

Store/StoreMap

public class Store
{
   public virtual int Id { get; private set; }
   public virtual string Name { get; set; }
}
public StoreMap()
{
   Id(x => x.Id);
   Map(x => x.Name);
}

Employee/EmployeeMap

public class Employee
{
  public virtual int Id { get; private set; }
  public virtual string FirstName { get; set; }
  public virtual string LastName { get; set; }
  public virtual Store Store { get; set; }
}

public class EmployeeMap : ClassMap<Employee>
{
  public EmployeeMap()
  {
    Id(x =&g开发者_JS百科t; x.Id);
    Map(x => x.FirstName);
    Map(x => x.LastName);
    References(x => x.Store).Cascade.All();
  }
}

Product/ProductMap

public class Product
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }
  public virtual double Price { get; set; }
  public virtual IList<Store> StoresStockedIn { get; private set; }

  public Product()
  {
    StoresStockedIn = new List<Store>();
  }

  public virtual void StockAt(Store store)
  {
    StoresStockedIn.Add(store);
  }
}

public class ProductMap : ClassMap<Product>
{
  public ProductMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    Map(x => x.Price);
    HasManyToMany(x => x.StoresStockedIn)
      .Cascade.All()
      .Table("StoreProduct");
  }
}

I've moved "Cascade" operations into the Product and Employee instead of Store. From the testing I've done, both HasMany and HasManyToMany associations seem to be working okay.

My question is if it's the right approach. Whether or not it will lead to something that I have not anticipated.


as far as I know, it's standard practice in nHibernate to have both ends of a relationship in your model classes (actually, it usually makes sense from the business point of view).
Although you don't have to do it (your example, I think, should work fine).
If you don't want to expose one (or both) ends you can always define them as private or protected.

p.s concerning json serialization: it's not recommended to serialize your model entities. this is for a few reasons, the top ones being:
1. the data you display to the user may be different from what you have in your entities (for example- you might want to present an employee with their name, Id, their store name and number of products they own. it would be hard to do that using your model classes).
2. it's quite possible that you'd have uninitialized collections in your objects (if you use lazy-loading). These do not get serialized.

For serialization, DTOs is the recommended approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜