外键约束失败,NHibernate,SQLite

时间:2013-08-21 17:07:41

标签: nhibernate fluent-nhibernate

我们有三个C#类:Branch,Team和Employee。分支机构有许多团队和许多员工。一个团队有很多员工。每位员工只属于一个团队。

实施1:

session.CreateQuery("DELETE FROM Employee e WHERE e.Branch.Id = 1"); // line 1
session.CreateQuery("DELETE FROM Team t WHERE t.Branch.Id = 1"); // line 2

在第2行,如果其中一个团队有员工,我们会得到“外键约束失败”。所以它就像第1行没有真正起作用。

实施2:

ICriteria criteria = session.CreateCriteria(typeof(Employee));
criteria.Add(NHibernate.Criterion.Expression.Eq(“Branch”, branch));
var e = criteria.List();
if (e != null && e.Count > 0) foreach (var e2 in e) this.Session.Delete(e2); 

ICriteria criteria = session.CreateCriteria(typeof(Team));
criteria.Add(NHibernate.Criterion.Expression.Eq(“Branch”, branch));
var t = criteria.List();
if (t != null && t.Count > 0) foreach (var t2 in t) this.Session.Delete(t2);

实现2有效,但我们认为它效率低,因为它从数据库中读取对象。我们如何让实现1工作?

另请注意:

class BranchMap : ClassMap<Branch> { ...
  HasMany(x => x.Teams).Table("TEAM").KeyColumn("BRANCH_ID").Inverse();
  HasMany(x => x.Employees).Table("EMPLOYEE").KeyColumn("BRANCH_ID").Inverse();

class TeamMap : ClassMap<Team> { ...
  HasMany(x => x.Employee).Table("EMPLOYEE").KeyColumn("TEAM_ID").Inverse();
  References(x => x.Branch).Column("BRANCH_ID").Not.Nullable().ForeignKey();

class EmployeeMap : ClassMap<Employee> { ...
  References(x => x.Team).Column("TEAM_ID").ForeignKey();
  References(x => x.Branch).Column("BRANCH_ID").Not.Nullable().ForeignKey();

0 个答案:

没有答案