簡體   English   中英

在編輯父對象時更新子對象

[英]Updating child objects when editing parent

我正在努力在“編輯帖子”操作中更新相關實體。

我有一個Job和一個JobNotes模型,如下所示:

public class Job
{
    public Job()
    {
        JobNotes = new List<JobNote>();
    }
    [Key]
    public int JobID { get; set; }
    public string jobName { get; set; }
    public ICollection<JobNote> JobNotes { get; set; }
}

public class JobNote
{
    [Key]
    public int JobNoteID { get; set; }
    public string Author { get; set; }
    public string Note { get; set; }
    public Job Job { get; set; }
}

我還使用Fluent API來映射我的關系:

(任何有關我是否正確完成此操作的反饋都非常歡迎!)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Job>()
                .HasMany(x => x.JobNotes)
                .WithOptional(y => y.Job);
}

問題是在我的Post方法中,我的JobNotes對象被添加到了父Job對象,但是沒有被保存到數據庫中。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(JobViewModel model)
{

    if (ModelState.IsValid)
    {
        var existingJob = db.Jobs
            .Include(x => x.JobNotes)
            .Single(c => c.JobID == model.Job.JobID);

        model.Job.JobNotes.Add(new JobNote
        {
            Author = "System",
            Note = "Job modified by " + User.Identity.Name
        });

        db.Entry(existingJob).CurrentValues.SetValues(model.Job);

        db.SaveChanges();

        return RedirectToAction("Details", new { id = model.Job.JobID });
    }
}

我做錯了什么? 在此先感謝您的幫助。

使用existingJobmodel.Job而不是model.Job添加新的JobNote

existingJob.JobNotes.Add(...);

調用SaveChanges ,EF將檢測到新筆記(基於已附加的existingJob ),並將其添加到上下文中,然后插入數據庫中。

順便說一下,您不需要在此過程中包括現有的注釋,因此可以刪除.Include(x => x.JobNotes)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM