我有一个向DbSet添加对象的问题。
class Word
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID {get;set;}
public virtual ICollection<Translation> Translations {get;set;}
public virtual ICollection<Inflection> Inflections {get;set;}
}
class Inflection
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID {get;set;}
public virtual Word Word {get;set;}
}
class Translation
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID {get;set;}
public virtual Word Word {get;set;}
public virtual ICollection<Sentence> Sentences {get;set;}
}
class Sentence
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID {get;set;}
public virtual Translation Translation {get; set;}
}
我这样做:
DatabaseContext.UserWord.Add(entity);
DatabaseContext.SaveChanges();
以下是我的关系配置:
modelBuilder.Entity<Translation>()
.HasRequired(x => x.Word)
.WithMany(x => x.Translations);
modelBuilder.Entity<Inflection>()
.HasRequired(x => x.Word)
.WithMany(x => x.Inflections);
modelBuilder.Entity<Sentence>()
.HasRequired(x => x.Translation)
.WithMany(x => x.Sentences);
我尝试创建Word对象:
{
"Id": "GUID"
"Translations": [
{
"Id": "GUID",
"Sentences": [
{
"Id": "GUID",
}
]
}
],
"Inflections": [
{
"Id": "GUID",
}
]
}
但“DatabaseContext.SaveChanges()”抛出异常:
INSERT语句与FOREIGN KEY约束冲突 “FK_dbo.Sentence_dbo.Word_WordId”。冲突发生在数据库中 “tempDatabase”,表“dbo.Word”,列“Id”。声明有 已被终止。
以下Word对象的一切正常:
{
"Id": "GUID"
"Translations": [
{
"Id": "GUID"
}
],
"Inflections": [
{
"Id": "GUID",
}
]
}
我做错了什么? 你能救我吗?
答案 0 :(得分:0)
您的sentence
模型看起来已发生变化,因为当word
引用translation
时,add-migration
具有外键,请尝试运行update-database
检查是否要查看更改并{{1}}(如果您使用代码优先迁移)