我在asp.net MVC5中遇到冲突错误

时间:2015-03-21 10:30:54

标签: entity-framework asp.net-mvc-4 entity-framework-4 asp.net-mvc-5 entity-framework-5

我在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;中。 声明已经终止。

enter image description here

1 个答案:

答案 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; }