NHibernate:使用Fluent NHibernate处理中间表的最佳方法?

时间:2008-11-24 19:09:03

标签: nhibernate fluent-nhibernate nhibernate-mapping fluent

如何在Fluent NHibernate中映射以下内容?

参见“18.3。客户/订单/产品”

http://www.hibernate.org/hib_docs/nhibernate/html/example-mappings.html

1 个答案:

答案 0 :(得分:6)

以下解决方案使用与示例中的解决方案相同的方法,并且生成的XML与此相同。为简洁起见,我省略了指定列名称等等。

<强>域

public class Customer
{
    private ISet<Order> orders = new HashedSet<Order>();

    public long Id { get; set; }
    public string Name { get; set; }
    public ISet<Order> Orders
    {
        get { return orders; }
        private set { orders = value; }
    }
}

public class Order
{
    public long Id { get; set; }
    public DateTime Date { get; set; }
    public Customer Customer { get; set; }
    public IList<LineItem> LineItems { get; private set; }
}

public class LineItem
{
    public int Quantity { get; set; }
    public Product Product { get; set; }
}

public class Product
{
    public long Id { get; set; }
    public string SerialNumber { get; set; }
}

<强>映射:

public class CustomerMap : ClassMap<Customer>
{
    public CustomerMap()
    {
        Id(x => x.Id)
            .GeneratedBy.Native();

        Map(x => x.Name);

        HasMany<Order>(x => x.Orders)
            .IsInverse()
            .AsSet();
    }
}

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        Id(x => x.Id)
            .GeneratedBy.Native();

        Map(x => x.Date);

        References<Customer>(x => x.Customer);
        HasMany<LineItem>(x => x.LineItems)
            .Component(c =>
                {
                    c.Map(x => x.Quantity);
                    c.References<Product>(x => x.Product);
                }).AsList();
    }
}

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Id(x => x.Id)
            .GeneratedBy.Native();

        Map(x => x.SerialNumber);
    }
}

要查看生成的XML映射,可以使用以下代码:

        Configuration config = new Configuration().Configure();
        PersistenceModel model = new PersistenceModel();

        model.addMappingsFromAssembly(typeof(CustomerMap).Assembly);
        model.Configure(config);

        model.WriteMappingsTo("your folder name here"); 

我希望它有所帮助。

/埃里克