Jannis Alexakis
Jannis Alexakis

Reputation: 1319

Image is not saved to database

I´m working on a test project, in order to learn and understand C# and WPF. I have a button that opens an explorer window. I want to save the selected file (an image) to the database (SQL 2012) in a column of type varbinary(max).

And I´m failing, the updated "selectedCellphone" with the image is not saved to the DB. While debugging, I noticed that the object "saveCellphones" is correct, the attribute "Photo" is the byte[] from the image. And the method throws no exception whatsoever.

private void importPhotoButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "Bilddateien (*.png;*.jpeg)|*.png;*.jpeg|Alle Dateien (*.*)|*.*";
    ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    ofd.ShowDialog();

    byte[] data = System.IO.File.ReadAllBytes(ofd.FileName);


    try
    {
        using (var context = new CellphoneManagerEntities())
        {
            if (selectedCellphone != null)
            {
                selectedCellphone.Photo = data;
                context.SaveChanges();
            }
        }
    }
    catch (System.Data.Entity.Infrastructure.DbUpdateException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Upvotes: 1

Views: 77

Answers (1)

oerkelens
oerkelens

Reputation: 5161

What is selectedCellPhone? It is not defined in the code you are posting.

I suspect you use selectedCellphone elsewhere in your code, and it is an entity that yuo have retrieved from your database using a context.

However, when you call SaveChanges() on a context, this is most certainly a different context from the one you used to retrieve your selectedCellphone!

There are no changes to save in the context that you are saving!

In order for any changes to be saved, you need to make the changes in the context that you are saving.

One way to do this, if you do not have the original context available, would be something like this:

using (var context = new CellphoneManagerEntities())
{
    var updateCellphone = context.CellPhones.FirstOrDefault(x => x.Id == selectedCellphone.Id);
    if (updateCellphone != null)
    {
        updateCellphone.Photo = data;
        context.SaveChanges();
    }
}

By the way, you are retrieving your byte[] even if nothing may be saved. Unless you use it elsewhere, why not move it inside you if:

updateCellphone.Photo = System.IO.File.ReadAllBytes(ofd.FileName);

Upvotes: 1

Related Questions