在我的系统中,我有两个实体 - ShoppingCart和ShoppingCartItem。相当通用的用例。但是,当我保存我的ShoppingCart时,没有任何项目正被保存到数据库中。NHibernate:使用流利Nhibernate保存子对象
在我的对象中,我创建了一个新的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;
}
我使用功能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
当我SaveOrUpdate我的购物车,为什么没有任何ShoppingCartItems也被保存?
请帮忙。
感谢
本
UPDATE: 结束语在交易providng我更多一些信息:
无法将NULL值插入列 'ShoppingCartId',表 “WroxPizza .dbo.ShoppingCartItems';列不允许有空值。 INSERT失败。该语句已终止。
这是因为它是一个新的购物车。
James Gregorys解决方案为我工作。 – 2010-06-30 13:53:48