【发布时间】:2014-08-21 07:57:00
【问题描述】:
我正在尝试使用 EF6 和 MVC 更新虚拟属性。 我的代码是这样的:
public async Task<ActionResult> Edit([Bind(Include = "Id,Title,Content,Image")] Recommendation recommendation, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
//we have an image - saving it to db
var image = Server.SaveFile(file, Request);
DB.Files.Add(image);
await DB.SaveChangesAsync();
//assign the new image to the recommendation
recommendation.Image = image;
}
recommendation.User = await GetLoggedInUserAsync();
DB.Entry(recommendation).State = EntityState.Modified;
await DB.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(recommendation);
}
图像保存在Files 表中。然而Recommendations 表中的Image_Id 列不会更新为新的Image_Id。我在这里错过了什么?
类:
public class Item
{
[Key]
public int Id { get; set; }
public virtual ApplicationUser User{ get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Content")]
public string Content { get; set; }
}
public class Recommendation : Item
{
[DisplayName("Image")]
public virtual File Image { get; set; }
}
public class File
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
【问题讨论】:
-
更新前
recommendation和其他Image有关系吗?同时显示您的课程,Image和Recommendation -
并非总是如此。但通常是的。
-
@YuliamChandra:我已经添加了课程
标签: entity-framework asp.net-mvc-5 entity-framework-6