NHibernate - not-null property reference a null or transient value

夙愿已清 提交于 2019-12-03 09:35:51

Another possibility is that you're saving an entire object graph, and that graph is circular, and items cannot be null. You could be giving NHibernate no legal order in which to do the inserts. (It should produce a better error message, but it produces this one).

Without seeing the rest of the source, it's hard to be of more help. Try removing entities from the mappings (and not saving them) until you can figure out what is causing the problem.

not sure if it helps but this did it for me.

<many-to-one name="Company" column="CompanyId" cascade="all" not-null="true"/>

cascade="all" was what I missed out before

I've had this problem recently and it has to do with the way NHibernate bi-directional relationships are persisted. You have the mapping correct and therefore NHibernate will perform the Patient insert no problem. Then NHibernate needs to take the key from Patients and cascade that into Insurances. Since the Patient does not yet exist, the keys do not exist and it cannot perform the second insert. The key is to set the relationship via code prior to persistence, something like this:

patient = new Patient();
patient.Insurances.Add( new Insurance{ Patient = patient } );
repository.Save( patient);

Now it was foreign to me that you have to set the Patient property on the collection item, but if you ignore persistence all together you will be setting this in code independent of your persistence strategy.

This worked for me. The important things here are that we have References with Cascade.All() and we don't have Inverse() on HasMany

public PatientMap()
{
    HasMany(x => x.Insurances)
        .WithKeyColumn("uid_Patient")
        .Cascade.All();

    ...
}

public InsuranceMap()
{
    References(x => x.Patient, "uid_Patient")
        .Not.Nullable()
        .Cascade.All();

    ...
}

It looks like the exception originates at line 25 of your RepositoryBase.cs file, presumably when a Save() is called on one of your transient objects. Which one is being saved?

Also, and it might be unrelated since I'm unfamiliar with the Fluent syntax, should the child object (the insurance in this case) have .Cascade.All on it? In standard XML schema syntax, only the parent mapping has cascade="all" on the collection of child objects.

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