2013-07-25 61 views
0

我正在給視頻添加一行,然後我想使用與視頻的物理文件名相同的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

假設您有一個自動遞增數據庫中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); 
    } 

由於「文件名」只是該ID的組合和文件擴展名,爲什麼不保存文件的擴展名並做串聯,當你需要引用的視頻。這會將您對數據庫的呼叫降低到一個,並在DB存儲上節省一點

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); 
    } 
+0

我已經忘記了v是一個參考。這意味着我可以在將其添加到視頻後對其進行修改。 至於你剛纔保存文件擴展名的建議。我會去做。非常有意義。謝謝。 – TheColonel26