您如何确保首先在EF代码中的表关系启用级联删除? [英] How do you ensure Cascade Delete is enabled on a table relationship in EF Code first?

查看:710
本文介绍了您如何确保首先在EF代码中的表关系启用级联删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用代码优先在表上启用CASCADE DELETE。当从头重新创建模型时,即使自动设置关系,也没有设置CASCADE DELETE。奇怪的是,它可以为一些具有多对多关系的表而启用此功能,您可能会认为它可能有问题。



设置:
表A< - 表B。



表B的FK指向表A的PK。



为什么这不起作用?

解决方案

可能的原因,你没有级联删除是你的关系是可选的。例如:

  public class Category 
{
public int CategoryId {get;组; }
}

public class Product
{
public int ProductId {get;组; }
public Category Category {get;组; }
}

在这个模型中,你会得到一个产品表,它有一个外键类别表,但此键为空,并且默认情况下,数据库中没有级联删除设置。



如果要保持关系,则有两个选项:



注释:

  public class Product 
{
public int ProductId {get;组; }
[必需]
public Category Category {get;组;
}

流利的API:




$ b .HasRequired(p => p.Category)
.WithMany();

在这两种情况下,将自动配置级联删除。



如果您希望将关系可选但WITH级联删除需要明确配置:

  modelBuilder.Entity< Product>()
.HasOptional(p => p.Category)
.WithMany()
.WillCascadeOnDelete(true);

编辑:在上一个代码片段中,您还可以简单地写入 .WillCascadeOnDelete )



文档


I would like to enable CASCADE DELETE on a table using code-first. When the model is re-created from scratch, there is no CASCADE DELETE set even though the relationships are set-up automatically. The strange thing is that it DOES enable this for some tables with a many to many relationship though, which you would think it might have problems with.

Setup: Table A <- Table B.

Table B's FK points to Table A's PK.

Why would this not work?

解决方案

Possible reason why you don't get cascading delete is that your relationship is optional. Example:

public class Category
{
    public int CategoryId { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public Category Category { get; set; }
}

In this model you would get a Product table which has a foreign key to the Category table but this key is nullable and there is no cascading delete setup in the database by default.

If you want to have the relationship required then you have two options:

Annotations:

public class Product
{
    public int ProductId { get; set; }
    [Required]
    public Category Category { get; set; }
}

Fluent API:

modelBuilder.Entity<Product>()
            .HasRequired(p => p.Category)
            .WithMany();

In both cases cascading delete will be configured automatically.

If you want to have the relationship optional but WITH cascading delete you need to configure this explicitely:

modelBuilder.Entity<Product>()
            .HasOptional(p => p.Category)
            .WithMany()
            .WillCascadeOnDelete(true);

Edit: In the last code snippet you can also simply write .WillCascadeOnDelete(). This parameterless overload defaults to true for setting up cascading delete.

See more on this in the documentation

这篇关于您如何确保首先在EF代码中的表关系启用级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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