Nhibernate PrimaryKey must be unique
I've set up a Nhibernate Project in C# with a Local SQLite Database, and if got an issue while saving my Nhibernate object, it says me that my primarykey is not unique, thats right but i added a Generator to my nhibernate-mapping.
Here is the Class:
public class Article
{
public virtual int ArticleId { ge开发者_运维问答t; set; }
public virtual string Name { get; set; }
public virtual double Price { get; set; }
public virtual string ArticleNumber { get; set; }
public virtual string Description { get; set; }
public virtual Sales Sales {get; set;}
}
And here is the Mapping File:
<class name="Article">
<id name="ArticleId">
<generator class="identity" />
</id>
<property name="Name" />
<property name="Price" />
<property name="ArticleNumber" />
<property name="Description" />
<many-to-one name="Sales" class="Sales" column="SalesId"/>
</class>
Im Creating Some Articles, and im adding it to Sales, if i want to save my Sales, it got this PrimaryKey exception.
Is there a known issue?
Very Thanks, Alex
Sales Mapping:
<class name="Sales">
<id name="SaleId" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Amount" />
<property name="Price" />
<bag name="OrderList" cascade="all">
<key column="ArticleId"/>
<one-to-many class="Article"/>
</bag>
</class>
public class Sales
{
public Sales()
{
if (this.orderList == null)
orderList = new List<Article>();
}
private IList<Article> orderList;
public virtual int SaleId { get; set; }
public virtual double Price { get; set; }
public virtual int Amount { get; set; }
public virtual IList<Article> OrderList
{
get
{
return this.orderList;
}
set
{
this.orderList = value;
}
}
}
I suggest setting up your identity mapping as such:
<id name="ArticleId" unsaved-value="0">
<generator class="native" />
</id>
Ensure the PK field is an identity field.
Then in your mapping for Sales:
<many-to-one name="Sales" class="Sales" column="SalesId" insert="true" update="true"/>
Same thing for your Sales mapping. Ensure it's id mapping has an unsaved value of 0 and the PK is marked as an identity field.
the problem was that i was using a Transaction, without Transaction it worked very well.
Thanks Jeffrey Jochum for your help.
精彩评论