Entity Framework Many for many database migrations

I am building an ASP MVC website using Entity Framework 4.4 with .NET Framework 4.0

I will add to my model the attitude of many, many like this:

  public class User {
    public int UserID { get; set; }
    public string Username { get; set; }
    public virtual ICollection<Tenant> Tenants { get; set; }
  }


  public class Tenant {
    public string TenantID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
  }

When I run the command Add-Migration, I get this migration class (I remove the Down method)

  public partial class TenantUsersManyToManyMigration : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.UserTenants",
                c => new
                    {
                        User_UserID = c.Int(nullable: false),
                        Tenant_TenantID = c.String(nullable: false, maxLength: 128),
                    })
                .PrimaryKey(t => new { t.User_UserID, t.Tenant_TenantID })
                .ForeignKey("dbo.Users", t => t.User_UserID, cascadeDelete: true)
                .ForeignKey("dbo.Tenants", t => t.Tenant_TenantID, cascadeDelete: true)
                .Index(t => t.User_UserID)
                .Index(t => t.Tenant_TenantID);
        }
  }
  • Why field names for TenantID and UserID are User_UserID and Tenant_TenantID, and not UserID and TenantID respectively.

  • How can I change the initial migration (or my model) to make cascadeDelete false? (currently I just change it manually).

+5
source share
2 answers

You can delete the cascade exclusion agreement as follows:

using System.Data.Entity.ModelConfiguration.Conventions;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

, . .

, Microsoft () FK Foreign Keys.

+4

, , . DbContext OnModelCreating :

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany(u => u.Tenants)
            .WithMany(t => t.Users)
            .Map(m =>
                {
                    m.ToTable("UserTenants");
                    m.MapLeftKey("UserId");
                    m.MapRightKey("TenantId");
                });
    }

, , , .WillCascadeDelete(false) . MSDN , .

+7

All Articles