2012-09-22 47 views
0

在我的ASP.NET MVC3應用程序(C#,SQL Server)ProductImagePath作爲字符串類型。當我保存圖像時,我想將產品的ID值設爲ImagePath。當我創建新的產品,我不知道會是什麼當前產品的IDdb.SaveChanges();如何在保存之前提前知道當前新對象的ID?

public ActionResult Create(Product product) 
    { 
     ..... 
     .....//How to know ID of this product in advance? 
     ..... 
     db.Products.AddObject(product); 
     db.SaveChanges(); 
    } 

我能找到的產品最後一個項目,並增加它:

currentID = lastID + 1; 

但是,也許是最後一次ID已刪除。結果不正確的..

回答

3

我建議以下方法:

//don't save the image yet, or save it in a temporary location 
db.Products.AddObject(product); 
db.SaveChanges(); 
product.ImagePath = //path including product.Id 
//save or move image to product.ImagePath 
db.SaveChanges(); 
1

我不能這樣做,你會怎麼做,如果兩個用戶同時嘗試建立產品?添加圖像,然後設置與產品的關係。

+0

產品最多可以有5張圖片。並且在每一天產品的圖像保存到相同的文件夾。明天,到其他文件夾。客戶希望觀看該文件夾並刪除他想要的任何圖像。他希望我設置產品和圖像之間的關係 –

+0

@Mores或者,您可以使用ajax發送數據,接收身份證並提供圖像上傳功能。 – webdeveloper