在asp.net mvc中更新Stub Entity的单列

时间:2017-02-16 08:20:58

标签: c# asp.net asp.net-mvc entity-framework

我有Book,每本书可以有多个Chapter。每个Chapter都有一个音频文件。如何更新章节子实体的单行?

这是我的模特:

public class Book
{
    public Book()
    {
        this.Chapters = new List<Chapter>();
    }
    [Key]
    public Int64 ISBN { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int BookID { get; set; }


    public string bookName { get; set; }

    public string bookAuthor { get; set; }

    [DataType(DataType.Currency)]
    public decimal bookPrice { get; set; }

    public virtual ICollection<Chapter> Chapters { get; set; }
}

public class Chapter
{
    public int ChapterId { get; set; }

    public string chapterName { get; set; }


    [ForeignKey("Book")]
    public Int64 ISBN { get; set; }
    public virtual Book Book { get; set; }
}  

在创建ActionResult中,我通过在章节模型中创建新对象来添加新Chapter,并使用book.Chapters.Add()

添加它
for (int i = 1; i < Request.Files.Count; i++)
{
    var mfile = Request.Files[i];

    if (mfile != null && mfile.ContentLength > 0)
    {
        var fileName = Path.GetFileNameWithoutExtension(mfile.FileName);
        Chapter _bChapter = new Chapter()
        {
            chapterName = fileName,
            chapterLink = BookDir +  mfile.FileName

    };
        book.Chapters.Add(_bChapter);
        mfile.SaveAs(Server.MapPath(_bChapter.chapterLink));


    }
}
编辑ActionResult中的

我使用HttpPostedFileBase

获取新音频
public ActionResult Edit(Book book, IEnumerable<HttpPostedFileBase> file)  
{
    if (ModelState.IsValid)
    {
        db.Entry(book).State = EntityState.Modified;

        //do some File operation to save audio in server folder

        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(book);
} 

但我不知道如何将新上传的音频保存到章节子实体

1 个答案:

答案 0 :(得分:1)

您可以更新Chapter,首先使用SingleOrDefault方法查找相关章节,然后修改chapterName属性并调用SaveChanges()方法,如下所示:

using (var context = new YourDbContext())
{
    var result = context.Chapter.SingleOrDefault(b => b.ISBN == book.ISBN);
    if (result != null)
    {
        result.chapterName = @"/root/my/audios";
        context.SaveChanges();
    }
}

编辑:

using (var context = new YourDbContext())
{
    var result = context.Chapter.Where(b => b.ISBN == book.ISBN).ToList();
    if (result.Any())
    {
        foreach(var chapter in result)
        {
           chapter.chapterName = @"/root/my/audios";
        }

        context.SaveChanges();
    }
}