开发者

FluentNHibernate Unidirectional One-To-Many Mapping

开发者 https://www.devze.com 2023-01-31 06:35 出处:网络
I have two classes. One is Order: public class Order { public virtual int Id { get; set; } public virtual IList<Product> Products { get; set; }

I have two classes. One is Order:

public class Order
{
    public virtual int Id { get; set; }
    public virtual IList<Product> Products { get; set; }
}

The other one is Product:

public class Product
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

They are fluently mapped like this:

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        Table("Orders");
        Id(x => x.Id, "Id");
        HasMany(x => x.Products)
            .KeyColumn("OrderId")
            .Cascade.All();
    }
}

public class Produ开发者_StackOverflow社区ctMap : ClassMap<Product>
{
    public ProductMap()
    {
        Table("Products");
        Id(x => x.Id, "Id");
        Map(x => x.Name);
    }
}

The database does NOT have a not-null constraint on the OrderId column of the Products table. Problem is: both the order and the products are being persisted, however the products are being persisted with a null value on the OrderId column.

Am I missing something?


instead of HasMany just use Reference

Reference(x => x.Products).Cascade.All();

Inverse on HasMany is an NHibernate term, and it means that the other end of the relationship is responsible for saving.


Well, as strange as it seems, we solved this issue here by re-working our Session management, using it to create an ITransaction in a using statement. Odd, but solved. Thanks everyone!


Try using:

HasMany(x => x.Products)
        .KeyColumn("OrderId")
        .Inverse()
        .Cascade.All();

Which(Inverse()) states that OrderId is on the Products table

0

精彩评论

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