Nhibernate stores id=0 as null

2019-04-12 06:26发布

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条回答
在下西门庆
2楼-- · 2019-04-12 07:14

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)

查看更多
登录 后发表回答