sjdweb
sjdweb

Reputation: 362

Introducing FOREIGN KEY constraint 'FK_dbo.Models_dbo.Makes_MakeId' on table 'Models' may cause cycles or multiple cascade paths

This is my first day I've spent exploring ASP.NET MVC 4. Specifically I'm using the Web API and obviously this issue is actually an MS SQL issue. I'm running EF migrations PM> Update-Database to get this error, but have seen it when first creating the models. My models are:

public class Car
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int MakeId { get; set; }
    public virtual Make Make { get; set; }

    public int ModelId { get; set; }
    public virtual Model Model { get; set; }
}

public class Make
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Model> Models { get; set; }
}

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }


    public int MakeId { get; set; }
    public virtual Make Make { get; set; }
}

The DB context is:

public class CarsContext : DbContext
    {
        public CarsContext() : base("name=CarsContext") { }
        public DbSet<Car> Cars { get; set; }
        public DbSet<Make> Makes { get; set; }
        public DbSet<Model> Models { get; set; }
    }
}

Would appreciate any help. My background is 5/6 solid of PHP and MySQL, so this is a steep learning curve.

Thanks.

Upvotes: 0

Views: 1504

Answers (1)

Ben Tidman
Ben Tidman

Reputation: 2139

Luke McGregor is correct. In addition to the way you fixed this you can override the default mapping that entity framework is giving you so that it doesn't cascade delete. In you CarsContext class you can override the OnModelCreating() method and specify your own mappings using fluent. This overrides what EF is trying to do by default. So you can do something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Car>()
            .HasOptional(x => x.Model)
            .WithMany(y => y.Cars) //Add this property to model to make mapping work
            .WillCascadeOnDelete(false);
}

This will still work with automatic migrations.

Hope that helps.

Upvotes: 1

Related Questions