NHibernate:使用Fluent Nhibernate来保存子对象

Ben*_*all 19 nhibernate nhibernate-mapping fluent-nhibernate

在我的系统中,我有两个实体 - ShoppingCart和ShoppingCartItem.相当通用的用例.但是,当我保存我的ShoppingCart时,没有任何项目保存到数据库中.

在我的对象中,我创建了一个新的ShoppingCart对象.

ShoppingCart cart = CreateOrGetCart();
Run Code Online (Sandbox Code Playgroud)

然后,我将从数据库中获得的现有产品添加到开头.

cart.AddItem(product);
Run Code Online (Sandbox Code Playgroud)

这只是将项添加到IList的简单包装器.

    public virtual void AddItem(Product product)
    {
        Items.Add(new ShoppingCartItem { Quantity = 1, Product = product });
    }
Run Code Online (Sandbox Code Playgroud)

然后我在Repository上调用SaveOrUpdate

Repository.SaveOrUpdate(cart);
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

   public T SaveOrUpdate(T entity)
    {
        Session.SaveOrUpdate(entity);
        return entity;
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用Fluent NHibernate进行映射:

    public ShoppingCartItemMap()
    {
        WithTable("ShoppingCartItems");

        Id(x => x.ID, "ShoppingCartItemId");
        Map(x => x.Quantity);

        References(x => x.Cart, "ShoppingCartId").Cascade.SaveUpdate();
        References(x => x.Product, "ProductId");
    }


    public ShoppingCartMap()
    {
        WithTable("ShoppingCarts");

        Id(x => x.ID, "ShoppingCartId");
        Map(x => x.Created);
        Map(x => x.Username);

        HasMany<ShoppingCartItem>(x => x.Items)
            .IsInverse().Cascade.SaveUpdate()
            .WithKeyColumn("ShoppingCartId")
            .AsBag();
    }
Run Code Online (Sandbox Code Playgroud)

数据库架构(SQL Server 2005)也非常通用:

CREATE TABLE [dbo].[ShoppingCarts]
(
[ShoppingCartID] [int] NOT NULL IDENTITY(1, 1),
[Username] [nvarchar] (50) NOT NULL,
[Created] [datetime] NOT NULL
)
GO
ALTER TABLE [dbo].[ShoppingCarts] ADD CONSTRAINT [PK_ShoppingCarts] PRIMARY KEY CLUSTERED ([ShoppingCartID])
GO



CREATE TABLE [dbo].[ShoppingCartItems]
(
[ShoppingCartItemId] [int] NOT NULL IDENTITY(1, 1),
[ShoppingCartId] [int] NOT NULL,
[ProductId] [int] NOT NULL,
[Quantity] [int] NOT NULL
)
GO
ALTER TABLE [dbo].[ShoppingCartItems] ADD CONSTRAINT [PK_ShoppingCartItems] PRIMARY KEY CLUSTERED ([ShoppingCartItemId])
GO
ALTER TABLE [dbo].[ShoppingCartItems] ADD CONSTRAINT [FK_ShoppingCartItems_Products] FOREIGN KEY ([ProductId]) REFERENCES [dbo].[Products] ([ProductId])
GO
ALTER TABLE [dbo].[ShoppingCartItems] ADD CONSTRAINT [FK_ShoppingCartItems_ShoppingCarts] FOREIGN KEY ([ShoppingCartId]) REFERENCES [dbo].[ShoppingCarts] ([ShoppingCartID])
GO
Run Code Online (Sandbox Code Playgroud)

当我SaveOrUpdate我的ShoppingCart时,为什么没有任何ShoppingCartItems也被保存?

请帮忙.

谢谢

更新:在交易中包装它提供了更多信息:

无法将值NULL插入"ShoppingCartId"列,表'WroxPizza.dbo.ShoppingCartItems'; 列不允许空值.INSERT失败.该语句已终止.

这是因为它是一个新车.

小智 1

尝试将 Session.SaveOrUpdate 包装在事务中,或者在事务之后直接强制刷新。