2012-09-17 81 views
2

我看了整個互聯網,仍然無法找到解決方案。什麼是SQL UPDATE的等效實體框架?

我試過附加方法:

public static void updatePhoto(string name, string albumName, string newName, string newPath) 
    { 
     //updates photo... no delete and adding... 
     var photo = new Image(){Label=newName, Path = newPath}; 
     using (var db = new EzPrintsEntities()) 
     { 
      db.Images.Attach(photo); 
      db.SaveChanges(); 
     } 

    } 

,但沒有做任何事情。

那麼問題是如何在下面的代碼中通過EF實現一個UPDATE到sql數據庫?

public static void updatePhoto(string name, string albumName, string newName, string newPath) 
    { 
     EzPrintsEntities db = new EzPrintsEntities(); 

    } 

回答

5

如果要更新現有的照片,你需要加載它,並改變現有的值:

public static void updatePhoto(string name, string albumName, string newName, string newPath) 
{ 
    using (var db = new EzPrintsEntities()) 
    { 
     // Load photo 
     var photo = db.Images.FirstOrDefault(i => i.Label == name && i.Album == albumName); 
     if (photo == null) 
     { 
      // no matching photo - do something 
     } 

     // Update data 
     photo.Label = newName; 
     photo.Path = newPath; 

     db.SaveChanges(); 
    } 

} 
+1

+ 1..sometimes我希望我是快:P – Thousand

0

的simplist方法是:

public static void updatePhoto(string name, string albumName, string newName, string newPath) 
{ 
    //updates photo... no delete and adding...  

    using (var db = new EzPrintsEntities()) 
    { 
     var photo = (from p in db.Images 
       where p.name == name && 
       p.albumname == albumName 
       select p).First(); 
     photo.name = newName; 
     photo.path = newPath; 
     db.SaveChanges(); 
    } 

} 

你只需使用Linq選擇現有的photo對象,修改它,然後SaveChanges()

0

您想要做的也是傳遞給updatePhoto方法Image實體上主鍵的值。然後,不是創建一個新的實體並附加它並保存上下文,而是從您的上下文中獲取Image實體,並且只更新其上的屬性。沿着這些線路

東西:

using (var db = new EzPrintsEntities()) 
{ 
    var image = db.Images.SingleOrDefault(i => i.Id == id); // Assuming Id is the PK on Image, and we sent in the PK in a variable called id. 
    if (image != null) 
    { 
     image.Label = newName; 
     image.Path = newPath; 

     db.SaveChanges(); 
    } 
    else 
    { 
     // Invalid PK value sent in, do something here (logging, error display, whatever). 
    } 
}