开发者

Why Fluent Nhibernate not saving the child objects?

开发者 https://www.devze.com 2023-03-10 10:35 出处:网络
My models, public class Person { public Person() { BloodPressureRecords = new List(); } public virtual int Id { private set; get; }

My models,


public class Person
    {
        public Person()
        {
            BloodPressureRecords = new List();
        }
        public virtual int Id { private set; get; }
        public virtual string Name { set; get; }
        public virtual int Age { get; set; }
        public virtual IList BloodPressureRecords {get;set;}

    }

    public class BloodPressure
    {
        public virtual int Id { private set; get; }
        public virtual DateTime RecordDate { set; get; }
        public virtual int BPU { get; set; }
        public virtual int BPL { get; set; }
        public virtual Person Person { get; set; }

    }

Mappings

public class PersonM开发者_开发技巧ap : ClassMap
    {
        public PersonMap()
        {
            Table("Persons");
            Id(d => d.Id).GeneratedBy.Identity();
            Map(d => d.Name).Not.Nullable().Length(50);
            Map(d => d.Age).Not.Nullable();
            HasMany(d => d.BloodPressureRecords).KeyColumn("PersonId").Cascade.All().Inverse();
        }
    }

    public class BloodPressureMap : ClassMap
    {
        public BloodPressureMap()
        {
            Table("BloodPressure");
            Id(d => d.Id).GeneratedBy.Identity();
            Map(d => d.BPL).Not.Nullable();
            Map(d => d.BPU).Not.Nullable();
            Map(d => d.RecordDate).Not.Nullable();
        }
    }

Now, I am trying to add two BloodPressure records. But, getting exception

Person p = session.Get(1);
            foreach (var item in bps)
            {
                BloodPressure pressure = new BloodPressure();
                pressure.BPL = int.Parse(item.BPLower);
                pressure.BPU = int.Parse(item.BPUpper);
                pressure.RecordDate = item.RecordDate;
                pressure.Person = p;
                p.BloodPressureRecords.Add(pressure);

            }

            session.SaveOrUpdate(p); 
            tran.Commit();

The exception
Cannot insert the value NULL into column 'PersonId', table 'HealthMonitor.dbo.BloodPressure'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated

What am I doing wrong?


Is session.Get(1) really returning a valid person. I don't think that's a valid call. Shouldn't it be:

session.Get<Person>(1)

or

session.Get(typeof(Person), 1)

You should probably double check to make sure what you are getting back is valid. I would guess it's not.

0

精彩评论

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