我有一个具有CompositeId的实体,它不会使用SaveOrUpdateCopy将新行插入数据库 . NHibernate生成的INSERT语句填充了“?”为每个领域的 Value . 使用SaveOrUpdate可以很好地插入它,使用SaveOrUpdateCopy或SaveOrUpdate可以很好地更新,并且任何没有CompositeId的实体都可以使用SaveOrUpdateCopy插入/更新 . 我不想创建if / then查找具有CompositeId的实体来决定它是否应该使用SaveOrUpdate或SaveOrUpdateCopy . 是否有一些技巧可以让SaveOrUpdateCopy与具有CompositeId的实体一起使用?
这是代码(更改名称以保护无辜者):
public class MyEntity
{
public virtual Int32 FirstProperty { get; set; }
public virtual string SecondProperty { get; set; }
public virtual string DataText { get; set; }
public override int GetHashCode( )
{
int hashCode = 0;
hashCode = hashCode ^ FirstProperty.GetHashCode() ^
SecondProperty.GetHashCode();
return hashCode;
}
public override bool Equals( object obj )
{
MyEntity toCompare = obj as MyEntity;
if( toCompare == null )
{
return false;
}
return ( GetHashCode() != toCompare.GetHashCode() );
}
}
public MyEntityMap()
{
CompositeId()
.KeyProperty(x => x.FirstProperty, "first_property")
.KeyProperty(x => x.SecondProperty, "second_property");
Map(x => x.DataText, "data_text")
.Nullable();
Table("dbo.my_entity");
}
数据库通话:
public MyEntity GetMyEntity(long firstProperty, string secondProperty)
{
using (var session = sessionFactory.OpenSession())
{
var result = from entity in
session.Linq()
where entity.FirstProperty == firstProperty
&& entity.SecondProperty== secondProperty
select entity;
return result.Count() > 0 ? result.First() : null;
}
}
数据库保存:
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
try
{
session.SaveOrUpdateCopy(entity);
transaction.Commit();
}
catch(Exception ex)
{
transaction.Rollback();
throw;
}
}
}
2 回答
将版本属性添加到复合键类,有关详细说明,请参阅this article .
嗨我使用compositeId与FluentnHibernate,但我的 Equals 和 GetHashCode 的实现是不同的 . 这一个类有7个字段为Key:
我希望这能帮到您 .