场景
我有2个表,人员及其活动,每次创建活动时,我还必须选择一个属于该活动的人。现在如何保存/始终更新人 personId 的 * LatestActivityId 记录?
这是因为我想跟踪此人的上一次活动数据。
非常感谢您的输入
这是我到目前为止所拥有的:
[HttpPost]
public ActionResult Create([Bind(Include = "PersonId" + "," + "ActivityTypeId")] dbo_Activities dbo_Activities)
{
if (ModelState.IsValid) {
// >>STUCK HERE<< //int SaveAsLatestActivity = db.dbo_Businesses.Max(p => p.ActivityId);
db.dbo_Activities.Add(dbo_Activities);
db.SaveChanges();
return RedirectToAction("Index");
}
// ComboBox >> selects person
ViewData["PersonId"] = new SelectList(db.dbo_Businesses, "PersonId", "FullName", dbo_Activities.PersonId);
return View(dbo_Activities);
}
我的活动模型
public class dbo_Activities
{
[Key]
[Column(Order = 0)]
[Required]
[Display(Name = "Activity Id")]
public Int32 ActivityId { get; set; }
[Display(Name = "Person Id")]
public Int32? PersonId { get; set; }
}
答案 0 :(得分:0)
您拥有PersonId
,因此在创建活动并获取ID后,从人员表中查询人员,将LatestActivityId
设置为刚创建的活动的ID,然后保存此人。您尚未发布完整的模型,因此我对某些属性的调用和模型的名称进行了一些假设,但应该看起来像这样:
[HttpPost]
public ActionResult Create([Bind(Include = "PersonId" + "," + "ActivityTypeId")] dbo_Activities dbo_Activities)
{
if (ModelState.IsValid) {
db.dbo_Activities.Add(dbo_Activities);
db.SaveChanges();
//set LatestActivityId on the person to the ActivityId of the entry that was just created
var person = db.dbo_Persons.Single(x => x.Id == dbo_Activities.PersonId);
person.LatestActivityId = dbo_Activities.ActivityId;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewData["PersonId"] = new SelectList(db.dbo_Businesses, "PersonId", "FullName", dbo_Activities.PersonId);
return View(dbo_Activities);
}