为什么没有相当于WillCascadeOnDelete的更新? [英] Why is there no update equivalent to WillCascadeOnDelete?

查看:459
本文介绍了为什么没有相当于WillCascadeOnDelete的更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您设置一个:EF代码中的许多关系,您可以选择是否应该像这样删除:

When you're setting up a one:many relationship in EF code-first, you can choose whether it should cascade on delete like so:

modelBuilder.Entity<Assessment>()
    .HasRequired(asmt => asmt.CreatedByUser)
    .WithMany(usr => usr.Assessments)
    .HasForeignKey(asmt => asmt.CreatedByUserId)
    .WillCascadeOnDelete(true);

这转换为SQL ON DELETE CASCADE 外部键定义的一部分,即

This translates to the SQL ON DELETE CASCADE part of a foreign key definition, ie.

ALTER TABLE [dbo].[Assessment]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Assessment_dbo.User_CreatedById] FOREIGN KEY([CreatedById])
REFERENCES [dbo].[User] ([UserId])
ON DELETE CASCADE
GO

但是,在Fluent API中似乎并没有类似的方法,允许您控制 ON UPDATE CASCADE ,即像 .WillCascadeOnUpdate()。为什么不这样?

However, there doesn't seem to be a similar method in the Fluent API that allows you to control the value of ON UPDATE CASCADE, ie. something like .WillCascadeOnUpdate(). Why not?

推荐答案

嗯,显然这个答案是你永远不会改变主键入ORM,即使DBMS支持更改主键。因为假设你永远不会改变主键,所以实体框架不需要允许你指定是否级联更新,因为这个想法是主键更新永远不会发生。

Well, apparently the answer to this is that you should never change the primary key in an ORM, even though DBMS's support the changing of the primary key. Because the assumption is that you will never change the primary key, there's no need for entity framework to allow you to specify whether to cascade on update, because the idea is that that primary key update will never happen.

但是,注意,即使实体框架ORM不允许您这样做,这仍然可以在大多数数据库中手动完成。如果您直接在数据库中手动进行主键更新,DBMS将仅使用其级联更新的默认行为。

Note, though, that this can still be done manually in most databases even if the entity framework ORM doesn't let you do it that way. The DBMS will just use its default behaviour for a cascade update if you do the primary key update, manually, directly in the database.

这篇关于为什么没有相当于WillCascadeOnDelete的更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆