我有一个带有CompositeId的实体,它不会使用SaveOrUpdateCopy将新行插入数据库。 NHibernate生成的INSERT语句填充了“?”为每个领域的价值。使用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; } } }
答案 0 :(得分:1)
将版本属性添加到复合键类,有关详细说明,请参阅this article。
答案 1 :(得分:0)
您好我将compositeId与FluentnHibernate一起使用,但 Equals 和 GetHashCode 的实现方式不同。这一个类有7个字段为Key:
defaults write com.apple.Terminal FocusFollowsMouse -bool false
defaults write com.apple.Terminal FocusFollowsMouse -string 2
defaults write com.apple.Terminal FocusFollowsMouse -string NO
我希望这会对你有所帮助。