내 시스템에는 ShoppingCart와 ShoppingCartItem의 두 엔티티가 있습니다. 상당히 일반적인 유스 케이스. 그러나 쇼핑 카트를 저장하면 항목이 DB에 저장되지 않습니다.NHibernate : Fluent Nhibernate를 사용하여 자식 객체 저장
내 개체 내에서 새로운 ShoppingCart 개체를 만듭니다.
ShoppingCart cart = CreateOrGetCart();
그런 다음 데이터베이스에서 가져온 기존 제품을 처음에 추가하십시오.
cart.AddItem(product);
이것은 IList에 항목을 추가하기위한 단순한 래퍼입니다.
public virtual void AddItem(Product product)
{
Items.Add(new ShoppingCartItem { Quantity = 1, Product = product });
}
I는 다음과 같습니다 저장소
Repository.SaveOrUpdate(cart);
에 될 saveOrUpdate를 호출
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) 상당히 일반적인 또한 :
내 shoppingCart가가 될 saveOrUpdateCREATE 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
, 왜 어떤 ShoppingCartItems는 저장되지 않는?
도와주세요.
감사
벤
UPDATE : 트랜잭션에 포장 좀 더 많은 정보를 원하시면 저를 providng :
, 테이블 을 열에 'ShoppingCartId'NULL 값을 삽입 할 수 없습니다 'WroxPizza .dbo.ShoppingCartItems '; 열이 널을 허용하지 않습니다. INSERT가 실패합니다. 그 진술서는 만료되었습니다.
이것은 새로운 카트입니다.
James Gregorys 솔루션이 나를 위해 일했습니다. –