如何编辑已存在的行

时间:2013-07-25 21:28:44

标签: asp.net-mvc entity-framework asp.net-mvc-4

我正在为视频添加一行,然后我想使用与视频的物理文件名相同的ID。所以我需要添加没有文件名的行,然后使用我得到的ID,然后使用文件名更新该行。我现在才确定如何做到这一点。

    public ActionResult UpVideo(Report Report, string VideoName, HttpPostedFileBase file)
    {
        Video v = new Video();
        v.Name = VideoName;
        v.Report = Report;
        db.Videos.Add(v);

        var filename = v.ID + "." + Path.GetExtension(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data/video_uploads"), filename);
        file.SaveAs(path);

        v.FileName = filename;

        //** update Row here with filename

        db.SaveChanges();


        //** redirect back to Report Details (need to figure out how do do this too)
        return RedirectToAction(Report);
    }

1 个答案:

答案 0 :(得分:1)

假设您的数据库中有ID的自动递增主键,则需要在引用ID属性之前调用保存更改。您必须将实体保存到数据库,以便可以分配ID。

public ActionResult UpVideo(Report Report, string VideoName, HttpPostedFileBase file)
    {
        Video v = new Video();
        v.Name = VideoName;
        v.Report = Report;
        db.Videos.Add(v);
        db.SaveChanges();

        var filename = v.ID + "." + Path.GetExtension(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data/video_uploads"), filename);
        file.SaveAs(path);

        v.FileName = filename;
        db.SaveChanges();   


        //** redirect back to Report Details (need to figure out how do do this too)
        return RedirectToAction(Report);
    }

由于'filename'只是Id和文件扩展名的组合,为什么不只是保存文件扩展名并在需要引用视频时进行连接。这会将您对数据库的调用减少到一个,并在数据库存储上节省一点

public ActionResult UpVideo(Report Report, string VideoName, HttpPostedFileBase file)
    {
        Video v = new Video();
        v.Name = VideoName;
        v.FileName = Path.GetExtension(file.FileName);
        v.Report = Report;
        db.Videos.Add(v);
        db.SaveChanges();

        var filename = v.ID + "." + v.FileName;
        var path = Path.Combine(Server.MapPath("~/App_Data/video_uploads"), filename);
        file.SaveAs(path);


        //** redirect back to Report Details (need to figure out how do do this too)
        return RedirectToAction(Report);
    }