How can I set up two navigation properties of the same type in Entity Framework

前端 未结 2 1927
梦毁少年i
梦毁少年i 2020-12-16 16:16

With code first EF4 (using CTP5) I can add a single navigation property along with the foreign key and it will respect the naming and only add the foreign key to the table a

相关标签:
2条回答
  • 2020-12-16 16:30

    I thought you were suppose to use the data annotation attribute

    [ForeignKey("FromPressTypeId")]
    

    etc.

    0 讨论(0)
  • 2020-12-16 16:35

    It's one of those scenarios that you need to drop down fluent API to get the desired schema:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AdapterFrameCapability>()
                    .HasRequired(afc => afc.FromPressType)
                    .WithMany()
                    .HasForeignKey(afc => afc.FromPressTypeID)
                    .WillCascadeOnDelete(true);
    
        modelBuilder.Entity<AdapterFrameCapability>()
                    .HasRequired(afc => afc.ToPressType)
                    .WithMany()
                    .HasForeignKey(afc => afc.ToPressTypeID)
                    .WillCascadeOnDelete(false);
    }
    

    Switching cascade delete off on one of the associations is intentional because otherwise SQL Server would throw out the following error:

    Introducing FOREIGN KEY constraint 'AdapterFrameCapability_ToPressType' on table 'AdapterFrameCapabilities' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint.

    So we need to switch it off on one of the associations like the way I did in the code.

    0 讨论(0)
提交回复
热议问题