开发者

How do I update the primary key using nhibernate

开发者 https://www.devze.com 2023-04-01 02:02 出处:网络
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.

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<C开发者_如何转开发ode>
    {
        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();
            }


Try 'assigned' id generator:

<class name="Dataset" table="Dataset" >
    <id name="id" column="id" type="String">
        <generator class="assigned" />
    </id>
    ...
</class>

Or

Id(x => x.Id).GeneratedBy.Assigned();

From NHibernate doc

5.1.4.7. Assigned Identifiers

If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号