我有两个班级:
public class Article
{
private ISet<IdentNumber> identNumbers = new HashedSet<IdentNumber>();
public virtual int ArticleId { get; set; }
public virtual string ArticleNumber { get; set; }
private virtual ISet<IdentNumber> IdentNumbers
public virtual void AddIdentNumber(IdentNumber identNumber)
{
if (identNumber.Article != null && identNumber.Article.identNumbers != null)
{
identNumber.Article.identNumbers.Remove(identNumber);
}
identNumber.Article = this;
this.IdentNumbers.Add(identNumber);
}
}
public class IdentNumber
{
public virtual int Number { get; set; }
public virtual int ArticleId { get; set; }
public virtual Article Article { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var x = obj as IdentNumber;
if (x == null)
{
return false;
}
return this.Number == x.Number && this.ArticleId == x.ArticleId;
}
public override int GetHashCode()
{
return (this.ArticleId + "|" + this.Number).GetHashCode();
}
}
这些对象应映射到旧数据库中的两个表Articles和IdentNumbers。 Artikles将ArtikleId(PK,int,not null)作为标识列。 IdentNumbers有一个复合PK。 Number(PK,int,not null)和ArticleId(PK,FK,int,not null)。
这是我到目前为止的映射文件:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Article" table="Articles">
<id name="ArticleId" unsaved-value="0">
<generator class="native" />
</id>
<property name="ArticleNumber" />
<set name="IdentNumbers" table="IdentNumbers">
<key column="ArticleId" />
<many-to-many unique="true" class="IdentNumber" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="IdentNumber" table="IdentNumbers">
<id name="ArticleId" column="ArticleId">
<generator class="foreign">
<param name="property">ArticleId</param>
</generator>
</id>
<property name="Number" />
</class>
</hibernate-mapping>
我想要上班的是这样的:
var article = new Article { ArticleNumber = "9876" };
var identNumber = new IdentNumber { Number = 1234 };
article.AddIdentNumber(identNumber);
session.Save(article);
我不能为我的生活得到这个复合pk,其中一部分是工作的外键。
感谢您的帮助。
编辑:
感谢Falcon,我得到了正确的映射。
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Article" table="Articles">
<id name="ArticleId" unsaved-value="0">
<generator class="native" />
</id>
<property name="ArticleNumber" />
<set name="IdentNumbers" table="IdentNumbers" cascade="all">
<key column="ArticleId" />
<one-to-many class="IdentNumber" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="IdentNumber" table="IdentNumbers">
<composite-id>
<key-many-to-one name="Article" column="ArticleId"/>
<key-property name="Number" />
</composite-id>
</class>
</hibernate-mapping>
答案 0 :(得分:1)
您不需要ArticleID!只需将Reference作为PK的一部分映射到Article类!当您设置IdentNumber的文章时,您已经确定了该部分密钥。