使用nhibernate在数据库中保存值

时间:2013-12-28 07:25:52

标签: c# sql nhibernate

我正在使用Nhibernate并希望在数据库中保存价值,如下所示。 这是我的商店类

 public class Store
    {
        public virtual int Id { get; protected set; }
        public virtual string Name { get; set; }
        public virtual Employee Staff { get; set; }

        public Store()
        {            Staff = new Employee();
           }
}

这是employee class

 public class Employee
    {
        public virtual int Id { get; protected set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual Store Store { get; set; }
    }

storemap

  public class StoreMap:ClassMap<Store>
    {
        public StoreMap() 
        {
            Id(x => x.Id);
            Map(x => x.Name);
            HasOne(x => x.Staff).WithForeignKey("store");
             HasManyToMany(x => x.Products).Cascade.All();        }
    }
}

employee map

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap ()
    {
        Id(x => x.Id);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        References(x => x.Store  ).WithColumns("store");
        References(x => x.Store2).WithColumns("store2");

    }

}

在商店表中我只保存表的名称。在员工表中,我正在保存员工的firstnamelastaname以及商店的foreignkey,以了解员工属于哪个表。 我写了这行代码

using (var trans = session.BeginTransaction())
                {
                    var ali = new Employee { FirstName = "fname", LastName = "lname", store=2 };
                    session.SaveOrUpdate(ali);
                    trans.Commit();
                }

但是这不能隐式转换int int models.store Employee.Store。这只是使用store = 2并且lastaname正在运行。请帮忙

1 个答案:

答案 0 :(得分:0)

在商店类中,为员工添加List

Public virtual Ilist<Employee> Employees {get; set;} // this list will save employees as per store 

并添加以下方法以添加员工

public virtual void add_employee(Employee emp)
    {
        emp.Store = this; // its current store value
        employees.Add(emp);
    }

并在添加新员工时调用此方法

using (var trans = session.BeginTransaction())
            {
                var ali = new Employee { FirstName = "fname", LastName = "lname"};
               var stor = new Store { Id = "1", Name= "Firststore"}; // for creating new store 
               AddEmployees(stor,emp);
                session.SaveOrUpdate(ali);
                session.SaveOrUpdate(stor);
                trans.Commit();
            }

           Public void AddEmployees(Store str, Employee emp)
           {
              str.add_employee(emp);
           }

试试这段代码。如果有任何疑问,请在此处发表评论

编辑:

当您不想使用一对多时,在添加员工之前创建商店并将其添加到员工

var stor = new Store { Id = "1", Name= "Firststore"};


var ali = new Employee { FirstName = "fname", LastName = "lname" , Store = stor};