Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework EntityFramework核心一对多配置_Entity Framework_Entity Framework Core - Fatal编程技术网

Entity framework EntityFramework核心一对多配置

Entity framework EntityFramework核心一对多配置,entity-framework,entity-framework-core,Entity Framework,Entity Framework Core,我正在尝试配置一对多的实体关系 如果父项有子项,则如何配置为不允许删除父项,而允许创建没有子项的父项 刷新EF核心文档示例。如果博客有帖子,但可以用帖子创建博客,我如何配置博客不允许删除。在DbContext的OnModelCreating方法中设置OnDelete限制。详情如下: 实体: public class Blog { public int Id{get; set;} public string Name{get; set;} public virtual

我正在尝试配置一对多的实体关系

如果父项有子项,则如何配置为不允许删除父项,而允许创建没有子项的父项


刷新EF核心文档示例。如果博客有帖子,但可以用帖子创建博客,我如何配置博客不允许删除。

在DbContext的OnModelCreating方法中设置OnDelete限制。详情如下:

实体:

public class Blog
{
    public int Id{get; set;}

    public string Name{get; set;}

    public virtual ICollection<Post> Posts{get; set;}
}

public class Post
{
    public int Id{get; set;}

    public string Name{get; set;}

    public int BlogId {get; set;}

    public virtual Blog Blog{get; set;}
}
DbContext中的配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Blog>()
        .HasMany(a => a.Posts)
        .WithOne(a => a.Blog)
        .HasForeignKey(a => a.BlogId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Restrict);
}

这是关于验证的。EF不会阻止您尝试删除有孩子的家长。我们只能帮助你,如果你表现出你的努力。