1

为了可以存储用户的屏幕首选项,我有 ScreenSettings 实体,我想在程序启动时检索它并在程序结束时保存。

出于这个原因,我不想保持上下文开放。

我想知道最好的方法来做到这一点。我尝试了以下方法,但是我对 SaveSettings 功能不满意,因为它会删除并重新添加对象。

如何保存对对象的更改而不实际替换它?

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
}
}
4

1 回答 1

2

您遇到了一个常见的模式,更新或插入,它很常见,以至于它有一个名字:upsert。当一个模式很常见时,通常也有一个共同的解决方案。

System.Data.Entity.Migrations一个扩展方法AddOrUpdate可以完全满足您的要求:

public void SaveSettings(ScreenSetting settings)
{
    using (var db = new Context())
    {
        db.ScreenSettings.AddOrUpdate(settings);
        db.SaveChanges();
    }
}
于 2013-02-09T12:28:38.750 回答