nhibernate - Fluent NHibernate——使用复合键保存实体

标签 nhibernate fluent-nhibernate

首先,我有下表:

CREATE TABLE CustomerHub (
   CustomerId INT NOT NULL,
   HubId INT NOT NULL
)

我已映射到此实体:

public class CustomerHub
{
   public int CustomerId {get;set;}
   public int HubId {get;set}

   //GetHashCode, Equals, Etc...
}

使用此映射:

public class CustomerHubMap : ClassMap<CustomerHub>
{
   UseCompositeId()
      .WithKeyProperty(x => x.CustomerId)
      .WithKeyProperty(x => x.HubId);
}

我遇到的问题是,当我创建 CustomerHub 类型的新实体并尝试保存它时,没有任何内容会保留到数据库中。我能够很好地检索所有内容,只是不能保存它们。例如:

//this will work
var x = session.CreateCriteria(typeof(CustomerHub)); 

//this will not
using (var trans = session.BeginTransaction()) 
{
   var custHub = new CustomerHub {CustomerId = 293, HubId = 1193};
   var y = session.SaveOrUpdate(custHub); 
   trans.Commit();
}

奇怪的是,没有抛出任何异常,它只是不执行任何操作。我启动了 NH Profiler(优秀的工具!),看起来它没有向数据库发出任何类型的插入命令。

想法?

注意:我意识到这个表看起来很像一个连接表(因为它在技术上是),并且最好作为另一个实体(例如客户)上的多对多关系......但由于一些极其扭曲的数据设计(即没有中心表)将连接表映射到实体并以这种方式使用它要简单得多。

最佳答案

编辑(放在顶部)

引用 NHibernate 文档:

Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

http://www.nhforge.org/doc/nh/en/index.html#mapping-declaration-id-assigned (5.1.4.7)

复合 ID 已分配生成器 =。

这又回到了复合 id = 吸吮:)

<小时/>

您没有发出刷新或提交。您可能习惯于使用诸如身份之类的在保存时发出 INSERT 的东西,但组合是由您的代码而不是数据库分配的,因此您需要刷新/提交才能进行插入。

<小时/>
var custHub = new CustomerHub {CustomerId = 293, HubId = 1193};
var y = session.SaveOrUpdate(custHub);
session.Flush();

using(var tx = session.BeginTransaction())
{
    var custHub = new CustomerHub {CustomerId = 293, HubId = 1193};
    var y = session.SaveOrUpdate(custHub);
    tx.Commit();
}
<小时/>

另外,请注意:使用复合键会让你讨厌你的生活。很多事情与复合键的工作方式不同,而且并不是立即显而易见的。基本上 NHibernate 可以完成较少的工作,因此您必须弥补这一不足。

关于nhibernate - Fluent NHibernate——使用复合键保存实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1189824/

相关文章:

c# - FluentNHibernate 查询多对多关系对象

c# - 父类的歧视值

c# - 如何使用 QueryOver 从内连接中按列排序?

NHibernate:保留一个带有子对象的对象

nhibernate - 如何使用 Fluent NHibernate 的类映射来映射 IDictionary<string, string> 并测试该映射?

c# - 流利的 : has invalid child element 'many-to-one' in namespace

nhibernate - 对 id 属性使用自定义类型

fluent-nhibernate - 通过自动映射使用 HasMany 映射同一类型的多个属性

asp.net-mvc - NHibernate-无法延迟初始化角色集合

c# - 更改 NHibernate 中的初始 LazyLoad 行为