EF 5:处置上下文时,OriginalValues丢失 [英] EF 5 : OriginalValues are lost when context is disposed

查看:128
本文介绍了EF 5:处置上下文时,OriginalValues丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是EF的新手。因此,为了测试乐观并发性,我使用了EF 5,WPF和一个已经创建的数据库.WPF项目包含 MainWindow 具有 TextBox1 用于通过主键搜索客户, TextBox2 用于客户名称编辑, textblock(txtLog)用来记录字段值和一个保存按钮。为了模拟并发访问,在 SQL Server 2008 Management Studio中,我执行了查询
更新客户端集r01_nomcli ='GGGGG',其中r01_codcli = '4112010002';
,然后点击保存按钮。它可以正常工作,并触发了 DbUpdateConcurrencyException ,但是该实体的原始值丢失了,并且其值
与当前值相同。这是因为使用块导致实体分离。为了解决这个问题,我必须在窗口的构造函数之前声明上下文,并在 Window_Loaded 事件中实例化该上下文。
还有另一个方法可以做到这一点吗? ??
帮助您了解使用EF的最佳实践,以及如何欢迎使用EF 5构建可重用的DAL。
谢谢。
在代码下面:

I am novice in EF. So to test the optimistic concurrency I used EF 5,WPF and an already created database.The WPF project contains a MainWindow Having TextBox1 for searching customer via primary key,TextBox2 for customer's name edit,a textblock (txtLog) to log Field values and a save button. To simulate Concurrency access, in SQL Server 2008 Management Studio i excute the query "update client set r01_nomcli = 'GGGGG' where r01_codcli = '4112010002';" before clicking on save Button. it works fine and DbUpdateConcurrencyException is fired, but The original values of the entity were lost and take the same values as those of the current values. This is because of the "using" block which causes the detachment of the entities. To solve this problem, i have to declare the context just before the constructor of the window and instantiate it in "Window_Loaded" event Is There another to make this ??? Helps about best practice of Using EF and how Building reusable DAL with EF 5 will be welcome. Thanks. Below the code :

 public partial class OptimisticConcurrency : Window
{

//client is an entity

    client _currentClient = null;

    public OptimisticConcurrency()
    {
        InitializeComponent();
    }


    //**************************TextBox1 PreviewKeyDown Event Handler
    private void TextBox_PreviewKeyDown_1(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {

            using (dbleaseEntities context = new dbleaseEntities())
            {
                _currentClient = context.client.Find(txtCode.Text);
                if (_currentClient == null)
                    MessageBox.Show("Customer " + txtCode.Text + " not found.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                    this.DataContext = _currentClient;
            }
        }
    }


//*****************Save Button Click Event Handler

private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        using (dbleaseEntities context = new dbleaseEntities())
        {
            context.Configuration.ValidateOnSaveEnabled = false;
            try
            {
                context.Entry(_currentClient).State = System.Data.EntityState.Modified;
                context.SaveChanges();
                MessageBox.Show("Success.", "Save", MessageBoxButton.OK,    MessageBoxImage.Information);
            }
            catch (DbEntityValidationException ex)
            {
                string ss = "";
                foreach (var error in ex.EntityValidationErrors)
                    ss = string.Join(Environment.NewLine, error.ValidationErrors.Select(v => v.ErrorMessage));
                MessageBox.Show(ss, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
             }

            catch (DbUpdateConcurrencyException ex)
            {
                string StrValues= "";
                DbPropertyValues ov = ex.Entries.Single().OriginalValues;
                DbPropertyValues cv = ex.Entries.Single().CurrentValues;
                DbPropertyValues dv = ex.Entries.Single().GetDatabaseValues();

                StrValues=  "Original value  : " + ov["r01_nomcli"] + Environment.NewLine +
                            "Current value   : " + cv["r01_nomcli"] + Environment.NewLine +
                            "Database value  : " + dv["r01_nomcli"];

               txtLog.Text = StrValues



            }
        }
    }


推荐答案

您大约有三个选择


  1. 执行您现在正在做的事情-即保持对象与上下文的连接

  2. 使用自我跟踪实体: http://blogs.msdn.com/b/efdesign/ archive / 2009/03/24 / self-tracking-entities-in-the-entity-framework.aspx

  3. 使用GetDatabaseValues

这篇关于EF 5:处置上下文时,OriginalValues丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆