简体   繁体   中英

EF code first - Table with 2 or more child relationships of the same type

This has been asked a few times, but solutions I have seen so far have not solved the issue.

I have tables like this.

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

   public int TableBRefAId {get; set;}

   public int TableBRefBId {get; set;}

   [Required]
   public TableB ItemA {get;set;}

   [Required]
   public TableB ItemB {get;set;}
}

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

    public virtual IList<TableA> TableAList { get; set; }
}

and then in the DataContext I have this.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TableA>()
            .HasRequired<TableB>(p => p.ItemA)
            .WithMany(pp => pp.TableAList )
            //.HasForeignKey(x => x.TableBRefAId)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<TableA>()
            .HasRequired<TableB>(p => p.ItemB)
            .WithMany(pp => pp.TableAList )
            //.HasForeignKey(x => x.TableBRefBId)
            .WillCascadeOnDelete(false);
    }

When I try to run "Add-Migration AddedTableA" I get the following error.

Schema specified is not valid. Errors: The relationship 'TableA_ItemA' was not loaded because the type 'TableB' is not available.

The way I need it to work it that TableA has 2 required properties of TableB.

If TableA is deleted, TableB is not affected.

If TableB is deleted, so is TableA

You should specify two collection for TableB entity to represent two references;

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

    public virtual IList<TableA> TableItemAList { get; set; }

    public virtual IList<TableA> TableItemBList { get; set; }
}

Then;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TableA>()
        .HasRequired<TableB>(p => p.ItemA)
        .WithMany(pp => pp.TableItemAList)
        //.HasForeignKey(x => x.TableBRefAId)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<TableA>()
        .HasRequired<TableB>(p => p.ItemB)
        .WithMany(pp => pp.TableItemBList)
        //.HasForeignKey(x => x.TableBRefBId)
        .WillCascadeOnDelete(false);
}

首先尝试使TableA类中的ItemA和ItemB虚拟,并在TableB类中添加TableA的另一个虚拟列表

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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