我在设置实体中的表之间的关系方面遇到了一个小问题。基本上我有三个模型:AppUser
,Assignment
和CompletedAssignment
。
public class AppUser
{
[Display(Name = "Your Id:")]
public int ID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public virtual ICollection<CompletedAssignment> CompletedAssignments { get; set; }
}
public class Assignment
{
[Display(Name="Assignment ID")]
public int ID { get; set; }
[Display(Name = "Assignment Name")]
public string AssignmentName { get; set; }
[Display(Name = "Assignment Description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public Assignment(){
this.CreationDate = DateTime.Now;
}
public virtual ICollection<CompletedAssignment> Assignments { get; set; }
}
public class CompletedAssignment
{
public int ID { get; set; }
[Display(Name = "Assignment ID")]
public int AssignmentID { get; set; }
[Display(Name = "Student ID")]
public int AppUserID { get; set; }
public DateTime CompletionDate{get;set;}
public CompletedAssignment()
{
this.CompletionDate = DateTime.Now;
}
public virtual Assignment Assignment { get; set; }
public virtual AppUser AppUser { get; set; }
}
我(想)我在它们之间配置了一组关系:AppUser
和CompletedAssignment
之间的一对多关系,以及Assignment
和CompletedAssignment
之间的一对多关系所以我在CompletedAssignment
表中有两个外键。
当我尝试使用用户提供的两个外键ID向数据库添加新CompletedAssignment
时,会出现问题。
错误消息:
&#34; INSERT语句与FOREIGN KEY约束冲突 \&#34; FK_dbo.CompletedAssignments_dbo.AppUsers_AppUserID \&#34 ;.冲突 发生在数据库\&#34; aspnet-name-20160527092700 \&#34;,表中 \&#34; dbo.AppUsers \&#34;,列&#39; ID&#39;。\ r \ n该声明已被终止。&#34;
导致它的代码:
[HttpPost]
public ActionResult Create([Bind(Include = "ID,AssignmentID,UserID,CompletionDate")] CompletedAssignment completedAssignment)
{
if (ModelState.IsValid)
{
db.CompletedAssignments.Add(completedAssignment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(completedAssignment);
}
到目前为止,我从SQL中记得这个错误意味着已经为查询提供了不存在的密钥,但我已经检查了几次,并且两个表中都提供了密钥。我有点努力去理解实体数据库交互实际上是如何工作的,所以任何形式的帮助都会受到赞赏:)
答案 0 :(得分:1)
AppUserID没有价值。
你写了
[Bind(Include = "ID,AssignmentID,UserID,CompletionDate")]
应该是
[Bind(Include = "ID,AssignmentID,AppUserID,CompletionDate")]