在联合主键的对象关系映射文件中用什么标签表示
发布网友
发布时间:2024-10-22 11:56
我来回答
共1个回答
热心网友
时间:2024-11-15 14:48
您好,这样的:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Model.CompositeModel, Model" table="Composite">
<composite-id name="Pk" class="Model.PKModel, Model"> //name为主实体类的属性名
<key-property name="Id1" type="String" column="Id1"/>
<key-property name="Id2" type="String" column="Id2"/>
</composite-id>
<property name="Name" column="Name" type="String"/>
</class>
</hibernate-mapping>
CompositeModel.cs
public class CompositeModel
{
public virtual PKModel Pk { get; set; }
public virtual string Name { get; set; }
}
PKModel.cs
public class PKModel
{
public virtual string Id1 { get; set; }
public virtual string Id2 { get; set; }
/// <summary>
/// 判断两个对象是否相同,这个方法需要重写
/// </summary>
/// <param name="obj">进行比较的对象</param>
/// <returns>真true或假false</returns>
public override bool Equals(object obj)
{
if (obj is PKModel)
{
PKModel pk = obj as PKModel;
if (this.Id1 == pk.Id1 && this.Id2 == pk.Id2)
{
return true;
}
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
操作:
class Program
{
static void Main(string[] args)
{
ISessionFactory _sessionFactory = new Configuration().Configure().BuildSessionFactory();
using(ISession NSession = _sessionFactory.OpenSession())
{
IList<CompositeModel> ListComposite = NSession.Query<CompositeModel>().ToList();
foreach (var c in ListComposite)
{
Console.WriteLine(c.Name);
}
//查询单条
PKModel pk = new PKModel();
pk.Id1 = "01";
pk.Id2 = "1";
CompositeModel m = NSession.Get<CompositeModel>(pk);
Console.WriteLine(m.Name);
}
Console.ReadKey();
}
}