gpt4 book ai didi

nhibernate - Fluent NHibernate 多对一映射

转载 作者:行者123 更新时间:2023-12-04 14:36:13 25 4
gpt4 key购买 nike

我是 Hibernate 世界的新手。这可能是一个愚蠢的问题,但我无法解决它。我正在测试表的多对一关系并尝试插入记录。我有一个部门表和员工表。员工和部门在这里是多对一的关系。我正在使用 Fluent NHibernate 添加记录。下面的所有代码。请帮忙

SQL 代码

create table Dept (
Id int primary key identity,
DeptName varchar(20),
DeptLocation varchar(20)
);

create table Employee (
Id int primary key identity,
EmpName varchar(20),
EmpAge int,
DeptId int references Dept(Id)
);

类文件
public partial class Dept
{
public virtual System.String DeptLocation { get; set; }
public virtual System.String DeptName { get; set; }
public virtual System.Int32 Id { get; private set; }
public virtual IList<Employee> Employees { get; set; }
}

public partial class Employee
{
public virtual System.Int32 DeptId { get; set; }
public virtual System.Int32 EmpAge { get; set; }
public virtual System.String EmpName { get; set; }
public virtual System.Int32 Id { get; private set; }
public virtual Project.Model.Dept Dept { get; set; }
}

映射文件
public class DeptMapping : ClassMap<Dept>   
{
public DeptMapping()
{
Id(x => x.Id);
Map(x => x.DeptName);
Map(x => x.DeptLocation);
HasMany(x => x.Employees).Inverse().Cascade.All();
}
}

public class EmployeeMapping : ClassMap<Employee>
{
public EmployeeMapping()
{
Id(x => x.Id);
Map(x => x.EmpName);
Map(x => x.EmpAge);
Map(x => x.DeptId);
References(x => x.Dept).Cascade.None();
}
}

我要添加的代码
        try
{
Dept dept = new Dept();
dept.DeptLocation = "Austin";
dept.DeptName = "Store";

Employee emp = new Employee();
emp.EmpName = "Ron";
emp.EmpAge = 30;

IList<Employee> empList = new List<Employee>();
empList.Add(emp);
dept.Employees = empList;
emp.Dept = dept;

IRepository<Dept> rDept = new Repository<Dept>();
rDept.SaveOrUpdate(dept);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

在这里我收到错误

InnerException = {"Invalid column name 'Dept_id'."} Message = "could not insert: [Project.Model.Employee][SQL: INSERT INTO [Employee] (EmpName, EmpAge, DeptId, Dept_id) VALUES (?, ?, ?, ?); select SCOPE_IDENTITY()]"

最佳答案

Mattias 的回答几乎是正确的,但 ForeignKey 用于模式生成。请尝试以下映射。此外,您还使用 CascadeAll 映射了Employees 集合。如果您删除一个部门,这将删除员工记录,这可能是不可取的。

public class DeptMapping : ClassMap<Dept>
{
public DeptMapping()
{
Id(x => x.Id);
Map(x => x.DeptName);
Map(x => x.DeptLocation);
HasMany(x => x.Employees).KeyColumn("DeptId").Inverse().Cascade.All();
}
}

public class EmployeeMapping : ClassMap<Employee>
{
public EmployeeMapping()
{
Id(x => x.Id);
Map(x => x.EmpName);
Map(x => x.EmpAge);
Map(x => x.DeptId);
References(x => x.Dept, "DeptId").Cascade.None();
}
}

关于nhibernate - Fluent NHibernate 多对一映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2472897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com