c# - 使用外键播种表
问题描述
我遇到了一个问题,因为它有一个外键约束,所以我无法为 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; }
}
解决方案
您的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);
推荐阅读
- python - 类型错误:不可散列类型“列表”,当我尝试使用正则表达式查找和计算文本文件中单个单词的重复次数时
- android - 无法在颤动中加载图像资产
- python - 无法在 Docker Continummio/anaconda3 上构建映像
- angular - 订阅后调用 next 时,如何获取订阅中 Observable 的最后发出值?
- python - 如何获取在 pyglet 中播放的当前源的名称?
- django - 将您自己的链接添加到 django 管理面板的标题
- flutter - 发布包时出错:pub 以退出代码 1 结束
- javascript - 使用 javascript 将数据导出到 csv 以获取产品表
- javascript - Firebase 文件上传工作了一段时间,但随后失败
- python - 没有为 selenium 定义名称驱动程序