简体   繁体   中英

Nhibernate stores id=0 as null

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM