流利的NHibernate参考仅在一个方向?

时间:2018-02-10 20:56:25

标签: c# nhibernate fluent-nhibernate

我试图找出如何让NHibernate使用1对多和多对1类型的关系。我有以下设置,但它似乎无法正常工作

public class Product {
     public Guid Id {get;set;}
     public string Name {get;set;}
     public string SKU {get;set;}
     public decimal MSRP {get;set;}
}

public class Order {
     public Guid Id {get;set;}
     public DateTime CreatedOn {get;set;}
     public IList<OrderLine> Lines {get;set;}
}

public class OrderLine {
     public Guid Id {get;set;}
     public Product Product {get;set;}
     public int Qty {get;set;}
     public decimal Price {get;set;}
}

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

     Map(x => x.Name);
     Map(x => x.SKU);
     Map(x => x.MSRP);
}

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

     Map(x => x.CreatedOn);

     // This doesn't seem to work as I get an error that OrderLine is not mapped
     HasMany(x => x.Lines);
}

public class OrderLineMap : ClassMap<OrderLine>
{
     Id(x => x.Id);

     Map(x => x.Qty);
     Map(x => x.Price);

     // This doesn't seem to work as I get an error the Product isn't mapped         
     // An association from the table OrderLine refers to an unmapped class: Product
     References(x => x.Product);
}

public static class NHibernateUtils
{
    public static ISessionFactory CreateSessionFactory(IPersistenceConfigurer persistenceConfigurer)
    {           
        return Fluently.Configure()
            .Database(persistenceConfigurer)
            .Mappings(m =>
            {
                m.FluentMappings.Add<ProductMap>();
                m.FluentMappings.Add<OrderLineMap>();
                m.FluentMappings.Add<OrderMap>();
            })
            .ExposeConfiguration(c => new SchemaExport(c).Create(false, true))
            .BuildConfiguration()
            .BuildSessionFactory();
    }
}

所以我很好奇 - 我做错了什么。注意:我不想为我的对象添加逆属性。因此OrderLine不需要对Order的引用,Product不需要引用Orders集合。我是否有限制?或者只是遗漏了一些简单的东西?

1 个答案:

答案 0 :(得分:0)

好的,我找出了主要问题 - 我在References()调用中错过了PropertyRef。看起来这是必需的?如果是,那么异常应该更具体吗?