实体框架6流利的api删除级联的n:n关系

时间:2019-01-08 07:05:37

标签: c# entity-framework-6 ef-fluent-api

在我的Entity Framework 6代码优先项目中,我有两个表具有多对多关系。

在Fluent API中,我定义了这样的关系:

        modelBuilder.Entity<Profile>()
            .HasMany(e => e.Recipes)
            .WithMany(e => e.Profiles)
            .Map(m => m.ToTable("ProfileRecipe")
            .MapLeftKey("Profiles_ID")
            .MapRightKey(new[] { "Recipes_Name" , "Recipes_Prefix" }));

在这种情况下,如何将删除时的级联设置为false?

.WillCascadeOnDelete(false);

不可用。

编辑1:

这是两个表的代码:

public partial class Profile
{
    public Profile()
    {
        Recipes = new HashSet<Recipe>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public virtual ICollection<Recipe> Recipes { get; set; }
}

public partial class Recipe
{
    public Recipe()
    {
        Profiles = new HashSet<Profile>();
    }

    [Key]
    [Column(Order = 0)]
    [StringLength(200)]
    public string Name { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(200)]
    public string Prefix { get; set; }

    public virtual ICollection<Profile> Profiles { get; set; }
}

编辑2:

级联删除已启用

您将在迁移脚本中看到它:

    CreateTable(
    "dbo.ProfileRecipe",
    c => new
            {
            Profiles_ID = c.Int(nullable: false),
            Recipes_Name = c.String(nullable: false, maxLength: 200),
            Recipes_Prefix = c.String(nullable: false, maxLength: 200),
            })
    .PrimaryKey(t => new { t.Profiles_ID, t.Recipes_Name, t.Recipes_Prefix })
    .ForeignKey("dbo.Profiles", t => t.Profiles_ID, cascadeDelete: true)
    .ForeignKey("dbo.Recipes", t => new { t.Recipes_Name, t.Recipes_Prefix }, cascadeDelete: true)
    .Index(t => t.Profiles_ID)
    .Index(t => new { t.Recipes_Name, t.Recipes_Prefix });

0 个答案:

没有答案