Charles
Charles

Reputation: 490

What is the Entity Framework equivalent of SQL UPDATE?

I looked all over the internet and still couldn't find a solution to this.

I tried the attach method:

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

    }

but that did not do anything at all.

So the question then is how do you implement an UPDATE to the sql database through EF in the code below?

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

    }

Upvotes: 2

Views: 1732

Answers (3)

Gromer
Gromer

Reputation: 9931

What you want to do is also pass to your updatePhoto method the value(s) for the primary key on your Image entity. Then instead of creating a new Image entity and attaching it and saving the context, you'll get the Image entity from your context, and just update the properties on it.

Something along these lines:

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).
    }
}

Upvotes: 0

JSK NS
JSK NS

Reputation: 3446

The simplist way would be:

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

}   

You simply select the existing photo object using Linq, modify it, and SaveChanges()

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564731

If you're updating an existing photo, you need to load it, and change the existing value:

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

}

Upvotes: 5

Related Questions