【发布时间】:2015-04-14 01:31:06
【问题描述】:
我有两个实体“Student”和“StudentImage”。我正在使用 MVC 5,我有一个表格,学生用图像填写他/她的个人资料,然后将其保存到 student 和 studentimage 表中。当没有以前的学生时,我可以同时插入学生和学生图片,但是当我的存储库进行更新时,只有学生会更新,学生图片不会更新。 *我已经完成了一个 sql profiler 检查,它看起来不像 studentimage 被用于任何更新查询。另一件事是它没有抛出任何错误。它完成并返回到我的视图。
这是我的实体
public class Student
{
public int StudentId { get; set; }
[Index(IsUnique=true)]
[Required]
[MaxLength(128)]
public string AspNetUserRefId { get; set; }
public virtual StudentImage StudentImage { get; set; } //one-to-one
// other members below
}
public class StudentImage
{
[Key, ForeignKey("Student")]
public int StudentId { get; set; }
public byte[] Image { get; set; }
public virtual Student Student { get; set; } // one-to-one
}
这是我在存储库中为我的学生提供的更新方法
public void InsertOrUpdate(Student student)
{
if (!context.Students.Any(u => u.AspNetUserRefId == student.AspNetUserRefId))
{
// New entity
context.Students.Add(student);
}
else
{
// Existing entity
context.Entry(student).State = EntityState.Modified;
}
}
这是我发布的用于保存的控制器方法编辑
[HttpPost]
public ActionResult Edit(EditStudentViewModel studentViewModel)
{
if (ModelState.IsValid)
{
byte[] array;
using (MemoryStream ms = new MemoryStream())
{
studentViewModel.StudentImageFileBase.InputStream.CopyTo(ms);
array = ms.GetBuffer();
}
var student = new Student
{
AspNetUserRefId = studentViewModel.AspNetUserRefId,
CatchPhrase = studentViewModel.CatchPhrase,
StartedPracticing = Convert.ToInt16(studentViewModel.SelectedYearId),
Location = studentViewModel.Location,
Education = studentViewModel.Education,
Work = studentViewModel.Work,
SelfDescription = studentViewModel.SelfDescription,
Inspirations = studentViewModel.Inspirations,
StudentId = studentViewModel.StudentId,
StudentImage = new StudentImage { Image = array, StudentId = studentViewModel.StudentId}
};
studentRepository.InsertOrUpdate(student);
studentRepository.Save();
return RedirectToAction("Edit", "Student");
} else {
return View();
}
}
【问题讨论】:
标签: c# asp.net-mvc entity-framework asp.net-mvc-5