NHibernate以一对一的关系保存对象

时间:2012-02-21 17:38:59

标签: nhibernate save relationship one-to-one

我是nHibernate的新手帮助我保存对象及其在基础中的连接。 我有两个表的基础:

  • person(idPerson,firstName,secondName,idService
  • service(idService,name)

餐桌服务有3个职位(金,银,辉煌)


映射:

 public class PersonMap:ClassMap<Person>
    {
        public PersonMap()
        {
            Id(x => x.id);
            Map(x => x.firstName);
            Map(x => x.lastName);
            Map(x => x.status);
            References(x => x.serviceType).Column("idServiceType");
            Table("Person");
        }
    }
    public class ServiceMap : ClassMap<ServiceType>
    {
        public ServiceMap()
        {
            Id(x => x.id);
            Map(x => x.serviceName);
            Table("Service");
        }
    }

我使用Repository中的下一个方法进行保存:

public void Saves(Person entity)
    {
        using (var session = hibernateHelp.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                ServiceRepository srp = new ServiceRepository();
                NHibernateUtil.Initialize(entity.service);
                session.Save(entity);
                transaction.Commit();
            }

        }
    }

我记下了日期(firstName =“我的”姓氏=“Go”状态= TRUE,serviceType =“gold”),然后我创建了一个人:

Person df=new Person{
           firstName="My",
           lastName="Go",
           status=true,
           serviceType=new ServiceType{serviceName="gold"}
           };

当我将它发送到Repository方法Save(见上文)时,映射正在工作并将新对象保存在表人员中并在表服务中创建新注释。 我不需要在表服务中创建新的注释,因为它包含一个。如何制作保护程序的方法以保存到表服务器的链接,但不创建新的??? 我感谢任何链接和建议。

1 个答案:

答案 0 :(得分:0)

Person newPerson = new Person
{
    FirstName = "My",
    LastName = "Go",
    Status = true,
    serviceType = session.Load<ServiceType>(idOfGold)  // returns the service if loaded or a proxy representing it which is enough to save the reference
    // or
    serviceType = session.Query<ServiceType>().Where(st.name == "gold").Single()
};

session.Save(newPerson);