在我的系统中,我有两个实体 - ShoppingCart 和 ShoppingCartItem。相当通用的用例。但是,当我保存我的 ShoppingCart 时,没有任何项目被保存到数据库中。
在我的对象中,我创建了一个新的 ShoppingCart 对象。
ShoppingCart cart = CreateOrGetCart();
然后,我将从数据库中获取的现有产品添加到开头。
cart.AddItem(product);
这只是将项目添加到 IList 的简单包装器。
public virtual void AddItem(Product product)
{
Items.Add(new ShoppingCartItem { Quantity = 1, Product = product });
}
然后我在存储库上调用 SaveOrUpdate
Repository.SaveOrUpdate(cart);
看起来像这样:
public T SaveOrUpdate(T entity)
{
Session.SaveOrUpdate(entity);
return entity;
}
我正在使用 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();
}
数据库架构 (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
当我保存或更新我的 ShoppingCart 时,为什么没有任何 ShoppingCartItems 也被保存?
请帮忙。
谢谢
本
更新:将其包装在交易中,为我提供了更多信息:
无法将值 NULL 插入到列“ShoppingCartId”、表“WroxPizza.dbo.ShoppingCartItems”中;列不允许空值。插入失败。该语句已终止。
这是因为它是一辆新推车。