首页 > 解决方案 > 使用外键播种表

问题描述

我遇到了一个问题,因为它有一个外键约束,所以我无法为 SQL 脚本做种,我尝试了 context.SaveChanges() 但它不起作用。有什么办法可以做到这一点?

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);
}

模型:

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

   public string Title { get; set; }
}

标签: c#sqlentity-framework

解决方案


您的Type班级没有Type名称的财产。您必须将Type属性更改为Title

List<Type> types = new List<Type>();

types.Add(new Type() { Title = "Fair" });//NOTE THIS
types.Add(new Type() { Title = "Great" });//NOTE THIS

context.Type.AddRange(types);
context.SaveChanges();

然后删除base.Seed(context);


推荐阅读