这是简单化了的场景:如何在一个一对多的关系发表评论添加到实体
我有一个类Device
[Key]
public int Id { get; set; }
[MaxLength(50)]
public String Name { get; set; }
[Required]
public Category Category { get; set; }
[Required]
public Manufactor Manufactor { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Status> Status { get; set; }
和A类Comment
public int ID { get; set; }
public string Content { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateCreated { get; set; }
public string Author { get; set; }
public virtual Device Device { get; set; }
正如你所看到的设备的实体可以有很多评论,但一个评论只有一个设备。
在我的控制器我有这两个动作:
public ActionResult AddComment(int id)
{
Device device = db.Devices.Include(x => x.Comments).Where(dev => dev.Id == id).FirstOrDefault();
if (device == null)
{
return HttpNotFound();
}
return View(device);
}
[HttpPost, ActionName("CommentAdded")]
public ActionResult CommentAdded(int id)
{
Device device = db.Devices.Find(id);
db.Entry(device).State = EntityState.Modified;
db.Devices.AddOrUpdate(device);
foreach(var comment in device.Comments)
{
db.Comments.AddOrUpdate(comment);
}
db.SaveChanges();
return View("Index");
}
到现在为止一切都显得直截了当。但是suddently我不知道如何创建一个视图中,我能做到这三两件事:
- 显示设备
- 显示的名称所有评论
- 显示一个文本框添加其他评论
我可以轻松实现1和2,但我不知道如何添加其他评论,然后提交表单。
AddComment.cshtml:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Device</h4>
<hr />
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.DisplayFor(model => model.Name)
</div>
<div class="col-md-6">
<br/>
<div class="row">
@Html.EditorFor(model => model.Comments)
</div>
@foreach (var comment in Model.Comments)
{
<div class="row">
<div class="col-md-4">
<strong>
@Html.DisplayFor(model => comment.Author)
</strong>
</div>
<div class="col-md-4">
<strong>
@Html.DisplayFor(model => comment.DateCreated)
</strong>
</div>
<div class="col-md-4">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
@Html.DisplayFor(model => comment.Content)
</p>
</div>
</div>
}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
眼下的问题是:我需要什么,我认为(POS控制器)来改变,才能够添加到设备的另一个选择评论?
与代码相关但不是问题的症结:在上下文中的DbSets上使用AddOrUpdate时要小心。这种扩展方法真的是用于迁移,并不总是像在播种领域之外期望的那样行事。 –