Nhibernate stores id=0 as null

僤鯓⒐⒋嵵緔 提交于 2019-12-06 08:18:55

问题


I have small problem with nHibernate (fluent) I have two objects, one contains another - a parent and a child (predefined objects, readonly).

mappings:

public class ParentClass
{
    public virtual int Id { get; set; } 
    public virtual ChildClass Metoda { get; set; }
}

public ParentClassMap() {
        Table("Wyceny");
        Id(x => x.Id).Column("Id").GeneratedBy.TriggerIdentity();
        References(x => x.Metoda).Column("RMW_ID");
}

public ChildClass 
{
        public virtual int Id { get; set; }
        public virtual string Nazwa { get; set; }
}

public ChildClassMap()
{
            Table("Metody");
            Id(x => x.Id).Column("Id");
            Map(x => x.Nazwa).Column("Nazwa_met");
}

Everything works perfectly until I chose child object with id = 0, reading still works for id=0, but when I'm trying to save or update Parent with correct ChildObject(readed previously from db through nHibernate), nHibernate stores null instead of value.

Any suggestions?

nHibernate 3.3.1.4000 fluent 1.4.0.0


回答1:


The issue here would be the unsaved-value. NHibernate must decide if operations with object will be insert or update. This decision comes from unsaved-value setting, which is by default for int set to 0.

Try to extend your mapping of a ChildClass:

public ChildClassMap()
{
   Table("Metody");
   Id(x => x.Id)
       .Column("Id")
       .UnsavedValue(-1);
   ...

See 5.1.4. id, cite:

unsaved-value (optional - defaults to a "sensible" value): An identifier property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session.

And here is nice Id mapping overview by Adam Bar (the second half of the article)



来源:https://stackoverflow.com/questions/23827253/nhibernate-stores-id-0-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!