为什么Fluent Nhibernate不保存子对象?

时间:2011-06-03 16:31:14

标签: nhibernate fluent-nhibernate

我的模特,


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 PersonMap : 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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

session.Get(1)真的归还了一个有效的人。我认为这不是一个有效的电话。不应该是:

session.Get<Person>(1)

session.Get(typeof(Person), 1)

您应该仔细检查以确保您获得的内容有效。我猜它不是。