Fluent Nhibernate 外键约束在删除时抛出异常
我有一对多关系:
对象报告类别:
Table("RCA_REPORT_CATEGORY");
Id(r => r.Id, "RCA_ID");
Map(r => r.Name, "RCA_NAME");
HasMany<Report>(r => r.Reports)
.Table("REP_REPORT")
.KeyColumns.Add("REP_RCA_ID").Cascade.None();
对象报告:
Table("REP_REPORT");
Id(r => r.Id, "REP_ID");
Map(r => r.Name, "REP_NAME");
References(r => r.Category, "REP_RCA_ID")
.Cascade.None();
REP_REPORT.REP_RCA_ID 上有一个外键引用 RCA_REPORT_CATEGORY.RCA_ID。
当我删除具有报告的 ReportCategory 时,它会起作用,并且报告表中的 REP_RCA_ID 列设置为 NULL。 但我不想要这样。我想要抛出一个异常,并告诉我该类别无法删除,因为它被报告使用并且违反了外键约束。我怎样才能做到这一点?
I have a one-many relation:
Object ReportCategory:
Table("RCA_REPORT_CATEGORY");
Id(r => r.Id, "RCA_ID");
Map(r => r.Name, "RCA_NAME");
HasMany<Report>(r => r.Reports)
.Table("REP_REPORT")
.KeyColumns.Add("REP_RCA_ID").Cascade.None();
Object Report:
Table("REP_REPORT");
Id(r => r.Id, "REP_ID");
Map(r => r.Name, "REP_NAME");
References(r => r.Category, "REP_RCA_ID")
.Cascade.None();
There is a foreign key on REP_REPORT.REP_RCA_ID which references RCA_REPORT_CATEGORY.RCA_ID.
When I delete a ReportCategory which has a Report, it works and the REP_RCA_ID column in the Report Table is set to NULL.
But I don't want that. I want an exception to be thrown and tell me that the category can't be deleted because it is used by a report and it violate the foreign key constraint. How can I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使类别引用不可为空:
那么数据库列 REP_RCA_ID 不能为 NULL,并且尝试删除非空类别将导致 SQL 异常。应首先在域模型中避免这种情况,并且仅当应用程序中存在错误时才应抛出 db 的异常。
也许您应该将 HasMany 集合标记为逆集合以避免一些问题:
Make Category reference not nullable:
Then the database column REP_RCA_ID cannot be NULL and attempt to delete not-empty category will lead to SQL exception. Such case should be avoided in your domain model first and the exception from db should be throwed only when there is a bug in your application.
Maybe you should mark HasMany collection as inverse to avoid some troubles: