Why is there no update equivalent to WillCascadeOn

2019-02-23 09:11发布

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);

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

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?

3条回答
贪生不怕死
2楼-- · 2019-02-23 09:44

Entity framework work with relationship through navigation properties, so ON UPDATE CASCADE allready switched on for all such relations.

Hmm and on the other hand i'm not sure that you can directly change primary key of entity from Entity Framework.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-23 09:58

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.

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-02-23 10:02

You can't change the primary key.

That is a bad practice in general, but particularly when working with an ORM.

查看更多
登录 后发表回答