UserControl和EF上下文配置

时间:2014-12-02 11:53:37

标签: c# winforms entity-framework dispose

我有一个UserControl,我使用我的EF上下文将数据从DB加载到dataGridView,以便用户进行一些更改:

    public partial class MyUserControl: UserControl
    {
        MyEntities context;

        public ViewMasterData()
        {
            InitializeComponent();
            createComboBoxTable();
        }

        private void MyUserControl_Load(object sender, EventArgs e)
        {
            context = new MyEntities();
        }

    // Other methods to fill the dataGridView and Save the data back to the DB

        private void SaveChanges()
        {
            context.SaveChanges();                
        }
    }

我想在离开UserControl时处理上下文(即导航到另一个UserControl),但似乎在UserControl的Dispose方法上调用context.Dispose()(在代码生成中)因为只有当我关闭整个WinForm时才会调用它。我不能使用“使用”,因为我需要保持上下文打开以执行更改然后保存。

问题是:当我离开UserControl时,如何才能正确处理上下文? 谢谢!

2 个答案:

答案 0 :(得分:1)

我认为保持EF上下文开放是不好的做法。而是在需要时创建上下文的新实例。实际上,将上下文包装在using语句中将通过垃圾收集自动处理它。

public partial class MyUserControl: UserControl
{
    // MyEntities context; i dont need this

    public ViewMasterData()
    {
        InitializeComponent();
        // createComboBoxTable();
    }

    private void MyUserControl_Load(object sender, EventArgs e)
    {
        using (var context = new MyEntitiesContext())
        {
            createComboBoxTable(context.MyEntities.ToList());
        }
    }

    private void SaveNewMyEntity(MyEntity newEntity)
    {
        using (var context = new MyEntitiesContext())
        {
            // some logic here to check for uniqueness etc

            context.MyEntities.Add(newEntity);
            context.SaveChanges(); 
        }
    }

    private void UpdateExistingMyEntity(MyEntity updatedEntity)
    {
        using (var context = new MyEntitiesContext())
        {
            context.Entry(updatedEntity).State = EntityState.Modified;
            context.SaveChanges(); 
        }
    }
}

<强>更新

我同意最好一次添加多个实体,你需要的只是一个foreach循环,也许还有一个bool属性,表明MyEntity实例是否已被更新。这样的事情是一个可能的解决方案:

private void UpdateExistingMyEntity(IEnumerable<MyEntity> updatedEntities)
{
    using (var context = new MyEntitiesContext())
    {
        foreach(MyEntity e in updatedEntities)
            context.Entry(e).State = EntityState.Modified;

        context.SaveChanges(); 
    }
}

当用户点击“保存”按钮...

private void saveBtn_Click(object sender, RoutedEventArgs e)
{
    IEnumerable<MyEntity> updatedEntities = myGridData.Where(o => o.HasBeenUpdated == true);

    UpdateExistingMyEntity(updatedEntities);

    foreach(MyEntity e in updatedEntities)
        e.HasBeenUpdated = false;
}

答案 1 :(得分:0)

直接在用户控制中使用EF是不好的做法。在另一个问题中查看here