Skip to content
Advertisement

Seeding a table with Foreign key

I encountered a problem where I cant seed an SQL script since it has a foreign key constraint, I tried context.SaveChanges() but it isn’t working. Is there any way how this can be done?

protected override void Seed(ApplicationDbContext context)
{
    List<Type> types = new List<Type>();
    types.Add(new Type() { Type = "Fair" });
    types.Add(new Type() { Type = "Great" });

    context.Type.AddRange(types);

    context.SaveChanges();

    var baseDir = AppDomain.CurrentDomain.BaseDirectory.Replace("\bin", string.Empty) + "\Paths";

    context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + "\Types.sql"));
    context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + "\Category.sql"));

    base.Seed(context);
}

Model:

public class Type
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; }

   public string Title { get; set; }
}

Advertisement

Answer

The question has been solved, the problem was that the data generated was not always the same, hence tweeking was made to INSERT the same data (Id) always the same

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement