可实体框架范围内重复使用代码所有的时间? [英] Can Entity Framework context be reused all the time in code?

查看:114
本文介绍了可实体框架范围内重复使用代码所有的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个我是有保存该有外键,因为对象来自多个构建对象连接到对象问题的问题对方直通外键,但他们每次都用不同的上下文中加载。例如:

 使用(VAR上下文=新EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)){
的IQueryable< Konsultanci> listaKonsultantow从K的context.Konsultancis
选择K =;

}



然后其他地方在代码中会有更多的背景用于获取更多的对象类型,如人员,培训,你的名字。



然后会有代码来保存它(简体):

 使用(VAR上下文=新EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)){
如果(context.Szkolenies.Any(T => t.SzkolenieID == currentSzkolenie.SzkolenieID)){$​​ b $ b context.Szkolenies。连接(currentSzkolenie);
context.ObjectStateManager.ChangeObjectState(currentSzkolenie,EntityState.Modified);
}其他{
context.Szkolenies.AddObject(currentSzkolenie);
}
context.SaveChanges();


}



通常试图挽救​​它就不后是多条错误消息



具有相同键的对象在ObjectStateManager已经存在。该ObjectStateManager无法跟踪多个对象使用相同的密钥。





这两个对象之间的关系不能被定义,因为它们连接到不同的ObjectContext对象



和其他几个人。



因此​​,要解决它,我已经声明私人EntityBazaCRM背景=新EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)之上我的类和重复使用这一切的时候没有把它变成使用。由于这个动作我没有附加任何东西之前,在保存或任何东西。我只是用相同的背景和附加任何外键使用我想 currentUczestnik.Szkolenie = szkolenie; 和currentUczestnik.Konsultanci =顾问;.它保存没有问题。



的问题:



它适用于一个小型的GUI,我有现在,是不是过于复杂。但是,如果我介绍多线程的,可以尝试使用相同的上下文来自全国各地不同对象的地方获得多个值(负载对象的GUI,ListView控件等)?会不会是回吹对我伤害了我严重?



在我的旧代码之前,我发现了实体框架我用的是:



 常量字符串preparedCommand = @SELECT ID FROM表,其中NAME =TEST;使用(VAR的SQLQuery =新的SqlCommand(preparedCommand,varConnection))

使用使用(SqlConnection的varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
(SqlDataReader的sqlQueryResult = sqlQuery.ExecuteReader())
,而(sqlQueryResult.Read()){
字符串ID = sqlQueryResult [ID]的ToString()。
}
}



基本上我是用每一个时间,我想连接到SQL。如果没有连接,就建立,如果有连接这将被重复使用,并与多线程没有问题。



有人能告诉我,我可以做我发现是工作的方式会发生什么问题呢?或者,也许这就是做最好的方式?


解决方案

但如果我介绍了多线程,尝试从所有获得多个值
在针对不同的对象(负载对象的GUI,
的ListView等)使用同一背景下的地方吗?会不会是回吹对我伤害了
我严重?




是的,是的,它会的。上下文基本上是在一个数据库连接之上的薄层 - 这不是线程安全的,所以您不能跨线程重复使用相同的背景。你正在寻找的是在你使用相同的上下文的工作单位,但一旦工作单元完成你处理的上下文。既然你用你自己仓库实现你将不得不建立在这些仓库的顶部工作的单位。


In this question I was having problem with saving objects that had foreign keys because Objects were build from multiple Objects connected to each other thru foreign keys but they were loaded using different context each time. For example:

  using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)) {
        IQueryable<Konsultanci> listaKonsultantow = from k in context.Konsultancis
                                select k;

  }

Then somewhere else in the code there would be more context used to get more object types like Persons, Training, you name it.

Then there would be code to save it (simplified):

        using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)) {
            if (context.Szkolenies.Any(t => t.SzkolenieID == currentSzkolenie.SzkolenieID)) {
                context.Szkolenies.Attach(currentSzkolenie);
                context.ObjectStateManager.ChangeObjectState(currentSzkolenie, EntityState.Modified);
            } else {
                context.Szkolenies.AddObject(currentSzkolenie);
            }
            context.SaveChanges();


       }

Usually after trying to save it there would be multiple error messages

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

or

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

and few others.

So to resolve it I have declared private EntityBazaCRM context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM); on top of my class and reused it all the time without putting it into using. Thanks to this action I didn't have to attach anything prior to saving or anything. I was just using same context and attached any foreign keys I wanted using currentUczestnik.Szkolenie = szkolenie; and currentUczestnik.Konsultanci = consultants;. It saved without problems.

To the question:

It works for a small GUI that I have now that isn't overcomplicated. But what if I introduce multithreading, try to get multiple values from all over the place for different objects (load object to GUI, to ListView etc) using the same Context? Won't it blow back on me hurting me severely ?

In my old code before I found out about Entity Framework I was using:

        const string preparedCommand = @"SELECT ID FROM TABLE WHERE NAME = "TEST"";
        using (SqlConnection varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
        using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
        using (SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader())
            while (sqlQueryResult.Read()) {
                string id= sqlQueryResult["id"].ToString();
            }
        }

which basically I was using for every single time I wanted to connect to SQL. If there was no connection, it would be established, if there was connection it would be reused and no problems with multithreading.

Can someone tell me what problems I can expect from doing it the way I found out to be working? Or maybe it's best way to do it?

解决方案

But what if I introduce multithreading, try to get multiple values from all over the place for different objects (load object to GUI, to ListView etc) using the same Context? Won't it blow back on me hurting me severely ?

Yes, yes it will. A context is basically a thin layer on top of a database connection - which is not thread safe, so you cannot reuse the same context across threads. What you are looking for is a unit of work within which you use the same context, but once that unit of work is completed you dispose the context. Since you use your own repository implementation you will have to build the unit of work on top of those repositories.

这篇关于可实体框架范围内重复使用代码所有的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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