什么是保存并首先使用代码还原断开连接的实体的正确方法?(What is the right way

2019-10-17 17:09发布

所以,我可以存储用户的喜好屏幕,我有我想要的程序启动时检索和程序结束时节省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
}
}

Answer 1:

你遇到了一个共同的模式,更新或插入,这是很常见的,它有一个名字:UPSERT。 当图案是常见的,通常还存在一个共同的解决方案。

System.Data.Entity.Migrations有一个扩展方法AddOrUpdate那不正是你想要什么:

public void SaveSettings(ScreenSetting settings)
{
    using (var db = new Context())
    {
        db.ScreenSettings.AddOrUpdate(settings);
        db.SaveChanges();
    }
}


文章来源: What is the right way to save and restore a disconnected entity using code first?