一对一的关系,ASP.NET MVC和参照完整性错误

时间:2016-07-05 10:28:20

标签: asp.net-mvc foreign-keys

我搜索过很多帖子,并了解到这是在EF中建立一对一关系的方式之一,但似乎编辑效果不佳。

public class Employee
{        
    [Key]
    public int EmpId { get; set; }
    public string Name{ get; set; }

    public int WorkingDateTimeId { get; set; }  
    public virtual WorkingDateTime WorkingDateTimes { get; set; } 

}

public class WorkingDateTime
{          
    [ForeignKey("Employees")] 
    public int WorkingDateTimeId { get; set; }
    public string Day { get; set; }

    public virtual Employee Employees { get; set; }

}

当我创作时,它会创造。但Employee实体中的WorkingDateTimeId属性始终为0.

<div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

<div class="form-group">
        @Html.LabelFor(model => model.WorkingDateTimes.Day, "Monday: ", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.WorkingDateTimes.Day, new { htmlAttributes = new { @class = "form-control time_element" } }) 
        </div>
    </div>

编辑时,我收到此错误:  发生了引用完整性约束违规:关系一端的“Employee.EmpId”的属性值与另一端的“WorkingDateTime.WorkingDateTimeId”的属性值不匹配。

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "EmpId,Name,WorkingDateTimes")] Employee employee)
    {

        db.Entry(employee).State = EntityState.Modified; // causing problem here
    }

我的一对一关系错了吗?需要做什么才能正确编辑并保存在db中?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您的关键定义是错误的。 WorkingDateTimeId是WorkingDateTime表的主键,它不是ForeignKey。从WorkingDateTime到Employee的ForeignKey键是EmpId。

public class Employee
{        
    [Key]
    public int EmpId { get; set; }
    public string Name{ get; set; } 
    public virtual WorkingDateTime WorkingDateTimes { get; set; } 
}

public class WorkingDateTime
{          
    [Key]
    public int WorkingDateTimeId { get; set; }
    [ForeignKey("Employees")]
    public int EmpId {get;set;}
    public string Day { get; set; }
    public virtual Employee Employees { get; set; }
}

这也是正确的

public class Employee
{        
    [Key]
    public int EmpId { get; set; }
    public string Name{ get; set; }
    [ForeignKey("WorkingDateTimes")]
    public int WorkingDateTimeId { get; set; }  
    public virtual WorkingDateTime WorkingDateTimes { get; set; } 
}

public class WorkingDateTime
{          
    [Key] 
    public int WorkingDateTimeId { get; set; }
    public string Day { get; set; }
    public virtual Employee Employees { get; set; }
}