我對流利NHibernate還是個新手。不知道我應該如何處理這個問題。如何在NHibernate中插入引用外鍵的子元素?
我有兩個實體:
public class Student
{
public virtual Guid StudentId { get; set; }
public virtual String Dept_id { get; set; }
public virtual String Name { get; set; }
public virtual int Age { get; set; }
public virtual String Address { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public virtual int Dept_id { get; set; }
public virtual String Dept_name { get; set; }
public virtual IList<Student> Students { get; set; }
public Department()
{
Students = new List<Student>();
}
}
和映射是:
public class DepartmentMap : ClassMap<Department>
{
public DepartmentMap()
{
Table("Department");
Id(x => x.Dept_id).Column("Dept_id");
Map(x => x.Dept_name).Column("Dept_name");
HasMany(x => x.Students).KeyColumn("Student_id").Inverse()
.Cascade.All();
}
}
public class StudentMap :ClassMap<Student>
{
public StudentMap()
{
Table("Student");
Id(x => x.StudentId).Column("Student_id").GeneratedBy.GuidComb();
Map(x => x.Name);
Map(x => x.Age);
Map(x => x.Address);
Map(x => x.Dept_id).Column("Dept_id");
References(x => x.Department).Column("Dept_id").Not.Nullable();
}
}
當我試圖儘可能插入:
StudentRepository rep = new StudentRepository();
Student s = new Student();
s.Name = txtname.Text;
s.Age = int.Parse(txtage.Text);
s.Address = txtaddress.Text;
s.Dept_id = dddept.SelectedItem.Value;
rep.Add(s);
它給我的錯誤是:
{"not-null property references a null or transient value nHibernateTest.Domain.Student.Department"}
嗯,我沒有理會,但我怎麼才能得到selectdepartment?我的意思是它可以只是一個空白對象的部門類? – Joy 2011-05-31 14:55:47
你如何得到你的部門ID?當我看到您使用上面的存儲庫時,您很可能會通過您的存儲庫獲取該部門。 – 2011-05-31 15:06:04
@Cole您好我試圖Mariusz建議現在的問題是它的錯誤提供:這個SqlParameterCollection Count = 5的無效索引5 – Joy 2011-06-02 04:27:42