【问题标题】:Seeding a table with Foreign key使用外键播种表
【发布时间】:2020-04-27 17:09:31
【问题描述】:

我遇到了一个问题,因为它有一个外键约束,所以我无法为 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# 类)所做的任何更改?
  • 是的,完全是@jdweng​​span>
  • 显示Type 模型
  • @FarhadZamani 编辑了它

标签: c# sql entity-framework


【解决方案1】:

您的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);

【讨论】:

  • 你会认为编译器会突出显示那个。
【解决方案2】:

问题已解决,问题是生成的数据并不总是相同,因此进行了 tweeking 以插入相同的数据 (Id) 始终相同

【讨论】:

  • 所以没有人会猜到这对你有帮助。强调您需要编写更好的问题并提供更多信息。很好,你把它整理好了。
猜你喜欢
  • 2018-03-29
  • 2021-08-22
  • 2020-01-27
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多