如何在NHibernate中插入引用外键的子元素?

时间:2011-05-31 10:55:38

标签: fluent-nhibernate

我还是Fluent 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"}

2 个答案:

答案 0 :(得分:1)

如果您要像在帖子中那样执行此操作,则会出现错误,因为您要发送Department对象的空数据。正如Cole W所说。您需要从数据库中比较要添加的部门的ID与现有部门的ID。

我将从Cole W回答中定义SelectedDepartment。您可以将其添加到存储库。

//repository
public Department SelectedDepartment(int id)
{
Department getDepartment = session.Get<Department>(id);
return getDepartment;
}
//controller
 s.Department = rep.SelectedDepartment(1) //for example department with id = 1

答案 1 :(得分:0)

在创建新学生时,您需要设置部门而不仅仅是Id。你需要一个单独的财产吗?我会从你的实体和你的映射类中删除这个属性,然后留在Department引用中。如果您需要部门ID,您可以通过Student.Department.Dept_id引用它。

基本上,您尝试在外键列中插入具有空值的实体。您需要将创建更改为以下内容:

    StudentRepository rep = new StudentRepository();
    Student s = new Student();
    s.Name = txtname.Text;
    s.Age = int.Parse(txtage.Text);
    s.Address = txtaddress.Text;
    s.Department = SelectedDepartment;  //SelectedDepartment is the actual department entity from the database
    rep.Add(s);