简体   繁体   English

EF 4.3.1中的级联行为,用于可选关系

[英]Cascade behaviour in EF 4.3.1 for optional relationships

I have an optional relationship from a Child to a Parent class. 我有一个从子级到父级的可选关系。 I would like to get an exception on SubmitChanges when the parent object is marked for deletion if there are still children around that reference it. 当父对象被标记为删除时,如果仍有周围的子对象引用,我想在SubmitChanges上得到一个例外。

The configuration I've tried is this (there is no navigation property from the parent to the children): 我尝试过的配置是这样(从父级到子级没有导航属性):

modelBuilder.Entity<Child>()
    .HasOptional<Parent>(child => child.Parent)
    .WithMany()
    .HasForeignKey(child => child.ParentId)
    .WillCascadeOnDelete(false);

Like this EF sets the children's ParentId property to null when deleting the parent, which is not what I want. 像这样,EF在删除父级时将子级的ParentId属性设置为null,这不是我想要的。

It works if the relationship is configured as required: 如果根据需要配置了关系,它将起作用:

modelBuilder.Entity<Child>()
    .HasRequired<Parent>(child => child.Parent)
    .WithMany()
    .HasForeignKey(child => child.ParentId)
    .WillCascadeOnDelete(false);

This throws an exception, which would be the desired behaviour. 这将引发异常,这将是所需的行为。 But the relationship has to be optional. 但是关系必须是可选的。 Is this possible with EF 4.3.1 using Code First? 使用代码优先功能的EF 4.3.1是否可以实现?

No. That is the difference between optional and required. 否。这是可选和必需之间的区别。 Required = must have a principal record and if you delete the principal record without cascading you will get an exception. 必需=必须具有主体记录,并且如果您在不级联的情况下删除主体记录,则会出现异常。 Optional = doesn't need a principal record and if you delete the principal record without cascading the FK is set to null. Optional =不需要主体记录,并且如果在不级联的情况下删除主体记录,则FK设置为​​null。

If you need anything else you must handle it yourselves. 如果您还需要其他任何东西,则必须自己处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM