代码第一外键配置 [英] Code First Foreign Key Configuration

查看:107
本文介绍了代码第一外键配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法保持父类与子类之间的多重关系。任何人都可以告诉我为什么我可以在父母中创建两个子引用,但不能创建三分之一?以下代码仅在第三个引用被注释掉时才起作用。

I am having difficulty maintaining multiple relationships between a parent class and it's children. Can anyone tell me why I can create two child references in the parent but not a third? The code below only works when the third reference is commented out.

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Child1Id { get; set; }
    public Child Child1 { get; set; }
    public int Child2Id { get; set; }
    public Child Child2 { get; set; }
    //public int Child3Id { get; set; }
    public Child Child3 { get; set; }
    public ICollection<Child> Children { get; set; }
}
public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public Parent Parent { get; set; }
}
public class CFContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithRequiredPrincipal(p => p.Child1)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Child>()
         .HasRequired(c => c.Parent)
         .WithRequiredPrincipal(p => p.Child2)
         .WillCascadeOnDelete(false);

        //modelBuilder.Entity<Child>()
        // .HasRequired(c => c.Parent)
        // .WithRequiredPrincipal(p => p.Child3)
        // .WillCascadeOnDelete(false);
    }
}


推荐答案

看起来你正在尝试从父母到子实体进行一对多的关系。在这种情况下,代码应该如下所示:

It looks like you are trying to make a one-to-many relation from Parent to Child entity. In that case the code should look like this:

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Child> Children { get; set; }
}
public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public Parent Parent { get; set; }
}

只需在Fluent API中指定关系即可您正在遵循关于导航属性和外键命名的默认约定。您将必须使用Fluent API和/或属性来配置您使用非约会名称的关系,例如,重命名ParentId某些其他需要您使用[ForeignKey(Parent)]属性标记它们的内容。

You don't have to specify the relation in Fluent API as long as you are following the default conventions regarding naming of the navigation properties and foreign key. You will have to use Fluent API and/or attributes to configure relations of you use non-convention names, eg renaming ParentId some something else requires you to mark it with at [ForeignKey("Parent")] attribute.

使用Fluent API最常见的用例是禁用级联删除(没有办法使用属性)。

The most common use case for using Fluent API is for disabling cascade delete (there is no way to do this with attributes).

这篇关于代码第一外键配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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