gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:22:03 24 4
gpt4 key购买 nike

首先,我有下表:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com