2

我查看了整个互联网,但仍然找不到解决方案。

我尝试了附加方法:

    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 实现对 sql 数据库的 UPDATE?

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

    }
4

3 回答 3

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();
    }

}
于 2012-09-17T18:39:09.303 回答
0

最简单的方法是:

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()

于 2012-09-17T18:40:49.513 回答
0

您还想要将实体updatePhoto上主键的值传递给您的方法。Image然后,您无需创建新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).
    }
}
于 2012-09-17T18:41:35.450 回答