Данный ключ отсутствует в словаре NHibernate на Delete

У меня проблемы с удалением объекта из базы данных с помощью NHibernate v3.

foreach (ShoppingCart s in query )
{
    _session.Delete(s);
    trans.Commit();
    break;
}

"Данный ключ отсутствует в словаре"

Там действительно нет более конкретной информации, чем это. В основном я использую две сущности, как показано ниже:

|    ShoppingCart   |==========> | Product          |

ShoppingCart PK: ShoppingCartID, ProductID (также является FK) Product PK: ProductID (не FK)

... Объект ShoppingCart, в котором много продуктов.

Моя картографическая сущность ShoppingCart выглядит следующим образом:

<class name="ShoppingCart" table="LC_SHOPPINGCART" lazy="true" >

<composite-id>
  <key-property name="CartID" column="CARTID" />
  <key-property name="ProductID" column="PRODUCTID" />
  <key-property name="Size" column="SIZE" />
  <key-property name="Color" column="COLOR" />
</composite-id>

<many-to-one foreign-key="ProductID" insert="false" update="false" lazy="false" name="Product">
  <column name="PRODUCTID" sql-type="INT" not-null="true" />
</many-to-one>

<property name="Quantity">
  <column name="QUANTITY" sql-type="INT" not-null="false" />
</property>

<property name="DateAdded">
  <column name="DATEADDED" sql-type="SMALLDATETIME" not-null="false" />
</property>

<property name="Price">
  <column name="PRICE" sql-type="MONEY" not-null="false" />
</property>

И класс Entity для ShoppingCart:

public ShoppingCart() { }
    [Key]
    public virtual string CartID { get; set; }
    public virtual int ProductID { get; set; }
    public virtual string Size { get; set; }
    public virtual string Color { get; set; }
    public virtual Product Product { get; set; }
    public virtual System.Nullable<int> Quantity { get; set; }
    public virtual DateTime DateAdded { get; set; }
    public virtual System.Nullable<decimal> Price { get; set; }

Мое сопоставление продуктов выглядит следующим образом:

<class name="Product" table="LC_PRODUCT" lazy="true" >

<id name="ProductID" column="ProductID">
    <generator class="native"></generator>
</id>

  <list name="ShoppingCarts"
        cascade="all-delete-orphan">
      <key column="ProductID"></key>
      <index column="CartID"></index>
      <one-to-many class="ShoppingCart"></one-to-many>
  </list>

<property name="Name">
  <column name="NAME" sql-type="NVARCHAR" not-null="false" />
</property>

<property name="Description">
  <column name="DESCRIPTION" sql-type="VARCHAR" not-null="false" />
</property>

<property name="Price">
  <column name="PRICE" sql-type="MONEY" not-null="false" />
</property>

<property name="Image1FileName">
  <column name="IMAGE1FILENAME" sql-type="NVARCHAR" not-null="false" />
</property>

<property name="Image2FileName">
  <column name="IMAGE2FILENAME" sql-type="NVARCHAR" not-null="false" />
</property>

<property name="OnCatalogPromotion">
  <column name="ONCATALOGPROMOTION" sql-type="BIT" not-null="false" />
</property>

<property name="OnDepartmentPromotion">
  <column name="ONDEPARTMENTPROMOTION" sql-type="BIT" not-null="false" />
</property>

<property name="Sizeable">
  <column name="SIZEABLE" sql-type="BIT" not-null="false" />
</property>

<property name="Colorable">
  <column name="COLORABLE" sql-type="BIT" not-null="false" />
</property>

<property name="DateAdded">
  <column name="DATEADDED" sql-type="SMALLDATETIME" not-null="false" />
</property>

<property name="TotalRemaining">
  <column name="TOTALREMAINING" sql-type="INT" not-null="false" />
</property>

</class>

... и соответствующий класс сущности Product:

public Product() { }
    [Key]
    public virtual int ProductID { get; set; }
    public virtual IList<ShoppingCart> ShoppingCarts { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual System.Nullable<decimal> Price { get; set; }
    public virtual string Image1FileName { get; set; }
    public virtual string Image2FileName { get; set; }
    public virtual bool OnCatalogPromotion { get; set; }
    public virtual bool OnDepartmentPromotion { get; set; }
    public virtual bool Sizeable { get; set; }
    public virtual bool Colorable { get; set; }
    public virtual DateTime DateAdded { get; set; }
    public virtual System.Nullable<int> TotalRemaining { get; set; }

Трассировка стека предоставляется следующим образом:

Ошибка сервера в приложении "/ElectronicsRob".

The given key was not present in the dictionary. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

Source Error: 


Line 106:            //db.lc_ShoppingCarts.DeleteOnSubmit(query);
Line 107:            //db.SubmitChanges();
Line 108:            new ShoppingCartRepository().DeleteProductFromCart( System.Convert.ToInt32  (Grid1.SelectedDataKey["ProductID"]), LinqShoppingCartAccess.cartID);
Line 109:            PopulateControls();
Line 110:        }


Source File: c:\inetpub\wwwroot\ElectronicsRob\LINQControls\ControlTemplates\LinqShoppingCart.ascx.cs    
Line: 108 

Stack Trace: 


[KeyNotFoundException: The given key was not present in the dictionary.]
NHibernate.Engine.StatefulPersistenceContext.RemoveEntity(EntityKey key) in d:\CSharp\NH\nhibernate\src\NHibernate\Engine\StatefulPersistenceContext.cs:435
NHibernate.Action.EntityDeleteAction.Execute() in d:\CSharp\NH\nhibernate\src\NHibernate\Action\EntityDeleteAction.cs:88
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) in d:\CSharp\NH\nhibernate\src\NHibernate\Engine\ActionQueue.cs:136
NHibernate.Engine.ActionQueue.ExecuteActions(IList list) in d:\CSharp\NH\nhibernate\src\NHibernate\Engine\ActionQueue.cs:125
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) in d:\CSharp\NH\nhibernate\src\NHibernate\Event\Default\AbstractFlushingEventListener.cs:241
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) in d:\CSharp\NH\nhibernate\src\NHibernate\Event\Default\DefaultFlushEventListener.cs:20
NHibernate.Impl.SessionImpl.Flush() in d:\CSharp\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1477
NHibernate.Transaction.AdoTransaction.Commit() in d:\CSharp\NH\nhibernate\src\NHibernate\Transaction\AdoTransaction.cs:190
ObjexxRepositories.ShoppingCartRepository.DeleteProductFromCart(Nullable`1 prodID, String cartID) in C:\Users\Rob\Documents\Visual Studio 2010\Projects\NGC6744\ObjexxRepositories\Concrete\ShoppingCartRepository.cs:78
LINQControls_LinqShoppingCart.Grid1_RowDeleting(Object sender, GridViewDeleteEventArgs e) in c:\inetpub\wwwroot\ElectronicsRob\LINQControls\ControlTemplates\LinqShoppingCart.ascx.cs:108
System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32 rowIndex) +814
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +431
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707

Любая помощь приветствуется, спасибо!

0 ответов

Другие вопросы по тегам