What is the right way to save and restore a discon

2019-08-15 03:24发布

So that I can store the user's screen preferences, I have ScreenSettings entity that I want to retrieve when the program starts and save when the program ends.

For this reason I don't want to keep the context open.

I am wondering about the best way to do this. I have tried the following however I am not comfortable with the SaveSettings function because it deletes and re-adds the object.

How do I save changes to the object without actually replacing it?

namespace ClassLibrary1
{
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

//Domain Class
public class ScreenSetting
{
    #region Properties

    public int Id { get; set; }

    [Required]
    public int WindowLeft { get; set; }

    [Required]
    public int WindowTop { get; set; }

    #endregion
}

// Context
public class Context : DbContext
{
    #region Properties

    public DbSet<ScreenSetting> ScreenSettings { get; set; }

    #endregion
}

// UI
public class UI
{
    #region Public Methods

    // Get the settings object
    public ScreenSetting GetSettings(int SettingsId)
    {
        var Db = new Context();
        ScreenSetting settings = Db.ScreenSettings.Find(SettingsId);
        if (settings == null)
        {
            settings = new ScreenSetting { Id = SettingsId, WindowTop = 100, WindowLeft = 100 };
            Db.ScreenSettings.Add(settings);
        }
        Db.Dispose();
        return settings;
    }

    // Save the settings object
    public void SaveSettings(ScreenSetting settings)
    {
        var Db = new Context();
        ScreenSetting oldSettings = Db.ScreenSettings.Find(settings.Id);
        if (oldSettings == null)
        {
            Db.ScreenSettings.Add(settings);
        }
        else
        {
            Db.ScreenSettings.Remove(oldSettings);
            Db.ScreenSettings.Add(settings);
        }
        Db.Dispose();
    }

    public void test()
    {
        ScreenSetting setting = this.GetSettings(1);
        setting.WindowLeft = 500;
        setting.WindowTop = 500;
        this.SaveSettings(setting);
    }

    #endregion

    #region Methods

    private static void Main()

    {
        var o = new UI();
        o.test();
    }

    #endregion
}
}

1条回答
再贱就再见
2楼-- · 2019-08-15 04:21

You ran into a common pattern, update or insert, which is so common that it's got a name: upsert. When a pattern is common, usually there also is a common solution.

In System.Data.Entity.Migrations there is an extension method AddOrUpdate that does exactly what you want:

public void SaveSettings(ScreenSetting settings)
{
    using (var db = new Context())
    {
        db.ScreenSettings.AddOrUpdate(settings);
        db.SaveChanges();
    }
}
查看更多
登录 后发表回答