我在asp.net MVC5中遇到冲突错误
这是我的Form模型的模型类
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid FormId { get; set; }
public Guid EntityBlockId { get; set; } // LinkToEntityBlockId
public virtual EntityBlock EntityBlock { get; set; }
这是我的EntityBlock模型的模型类
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid EntityBlockId { get; set; }
public virtual ICollection<Form> Form { get; set; }
并插入如下所示的值:
FormStaticMethodsController formStaticMethodsControllerObj = new FormStaticMethodsController();
Form form = new Form();
form.EntityBlockId = linkToBlockId;
formStaticMethodsControllerObj.CreateForm(form);
方法是:
public Guid CreateForm(Form form)
{
db.Forms.Add(form);
db.SaveChanges();
return form.FormId;
}
错误是:
INSERT语句与FOREIGN KEY约束冲突&#34; FK_dbo.Form_dbo.EntityBlock_EntityBlockId&#34;。冲突发生在数据库&#34; aspnet-Planetskool-20150303080110&#34;,table&#34; dbo.EntityBlock&#34;,column&#39; EntityBlockId&#39;中。 声明已经终止。
答案 0 :(得分:0)
如果您将EntityBlockId
定义为EntityBlock
的外键值,则应使用{{3}将EntityBlock
属性链接与字段EntityBlockId
相关联}:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid FormId { get; set; }
public Guid EntityBlockId { get; set; } // LinkToEntityBlockId
[ForeignKey("EntityBlockId")]
public virtual EntityBlock EntityBlock { get; set; }