[英]saving value in database using nhibernate
I am using Nhibernate
and want to save value in database as below. 我正在使用
Nhibernate
并想在数据库中保存值,如下所示。 This is my store class 这是我的商店课
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();
}
}
and this is employee class
这是
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
as 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(); }
}
}
and employee map
和
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");
}
}
in store table i am saving only name of the table. 在存储表中,我仅保存表的名称。 and in employee table i am saving
firstname
, lastaname
of employee and also foreignkey
of store to know that employee belong to which table. 在员工表我现在的储蓄
firstname
, lastaname
员工还foreignkey
储存知道员工都属于哪个表。 i write this line of code 我写这行代码
using (var trans = session.BeginTransaction())
{
var ali = new Employee { FirstName = "fname", LastName = "lname", store=2 };
session.SaveOrUpdate(ali);
trans.Commit();
}
but this cannot implicitly convert int int models.store Employee.Store. 但这不能隐式转换int int models.store Employee.Store。 this is only with store=2 first and
lastaname
are working. 仅在store = 2的情况下,first和
lastaname
起作用。 Please help 请帮忙
In store class add the List
for employee 在商店类中,添加员工
List
Public virtual Ilist<Employee> Employees {get; set;} // this list will save employees as per store
and add the following method for adding employee 并添加以下添加员工的方法
public virtual void add_employee(Employee emp)
{
emp.Store = this; // its current store value
employees.Add(emp);
}
and call this method when adding new employee 并在添加新员工时调用此方法
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);
}
try this code. 试试这个代码。 If any doubt just comment here
如有疑问,请在此处评论
Edit: 编辑:
When you dont want to use one to many, before adding employee create the store and add it to employee 当您不想使用一对多时,在添加员工之前创建商店并将其添加到员工
var stor = new Store { Id = "1", Name= "Firststore"};
var ali = new Employee { FirstName = "fname", LastName = "lname" , Store = stor};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.