如何使用 nhibernate 更新主键
我的一个表的主键是一个字符串。该字符串是我想在某个时间点更新的代码。我怎样才能在休眠中做到这一点。 请注意,有一个外键连接到该列,我需要将更新级联到该列。
为了便于讨论,我们假设我的映射如下
public class Code
{
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public class CodeMap : ClassMap<Code>
{
public CodeMap()
{
Table("BusinessCode");
Id(x => x.Id, "Id");
Map(x => x.Name, "Name").Nullable();
}
}
}
public class Data
{
public virtual int Key { get; set; }
public virtual Code DataCode{ get; set; }
public virtual string Desc { get; set; }
public class DataMap : ClassMap<Data>
{
public DataMap()
{
Table("Data");
Id(x=>x.Key,"Key");
Map(x => x.Desc).Column("desc");
References(x => x.Code, "BusinessCode").Nullable().Cascade.SaveUpdate();
}
}
}
表结构
BusinessCode Table
Id(nvarchar(100)) -primarykey
Name(nvarchar(1024))
Data Table
id(int) - auto generated primary key
businesscode(nvarchar(100)) - foreign key to BusinessCode Id
desc(nvarchar(1024))
这是我用来更新我的对象的代码
using (var trans = Session.BeginTransaction())
{
var modifiedSource = Session.Load<Code>(id);
modifiedSource.Id = "newId";
modifiedSource.Name = "new name";
Session.Update(modifiedSource);
trans.Commit();
}
The primary key for one of my tables is a string. THe string is a code which i would like to update at some point of time. How can I do this in nhibernate.
Please note there is a foreign key connected to this column which I need to cascade updates to.
For the sake of discussion let us assume my mapping is as below
public class Code
{
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public class CodeMap : ClassMap<Code>
{
public CodeMap()
{
Table("BusinessCode");
Id(x => x.Id, "Id");
Map(x => x.Name, "Name").Nullable();
}
}
}
public class Data
{
public virtual int Key { get; set; }
public virtual Code DataCode{ get; set; }
public virtual string Desc { get; set; }
public class DataMap : ClassMap<Data>
{
public DataMap()
{
Table("Data");
Id(x=>x.Key,"Key");
Map(x => x.Desc).Column("desc");
References(x => x.Code, "BusinessCode").Nullable().Cascade.SaveUpdate();
}
}
}
Table structure
BusinessCode Table
Id(nvarchar(100)) -primarykey
Name(nvarchar(1024))
Data Table
id(int) - auto generated primary key
businesscode(nvarchar(100)) - foreign key to BusinessCode Id
desc(nvarchar(1024))
here's the code which i use to update my object
using (var trans = Session.BeginTransaction())
{
var modifiedSource = Session.Load<Code>(id);
modifiedSource.Id = "newId";
modifiedSource.Name = "new name";
Session.Update(modifiedSource);
trans.Commit();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试“分配”id 生成器< /a>:
或
来自 NHibernate 文档
Try 'assigned' id generator:
Or
From NHibernate doc