0
点赞
收藏
分享

微信扫一扫

将不确定变为确定~LINQ查询包含对不同数据上下文上所定义项的引用

书写经典 2022-08-25 阅读 71

我们在使用linq查询时,你的数据源可能是linq to sql或者是ef产生的,但只要是使用linq的语法去实现一个查询,就有可能出现“查询包含对不同数据上下文上所定义项的引用”的异常,这个异常很明显,是你在进行join表关联查询时使用了多个不同的DataContext对象,这是linq不允许的。

有了这个异常,就会出现一些解决方案,以下是我们可能的一些做法:

1 使用全局的static对象,但对于linq to sql来说,在高并发时,这个static对象会抛出一些莫明奇秒的异常,那时,我们会说,linq to sql不如ado.net靠的住。

2 使用单例模型创建对象,保证它在所有对象中使用同一个DataContext对象,在不使用db时,记住要dispose它呀,呵呵(这也是目前我的做法)。

3 保存在做join关联表时,将它全部约束在DAL层,它们的使用同一个基类下的GetModel()来得到结果集,这样是可以的。(使着有点不爽,太局限了)

今天,我们主要来说一下第三种方式,因为前两种在我的博文中有说过,大家可以去参考。

好了,从数据基类开始吧!(只是简单的实践,不是真实项目中的代码幼,呵呵)

1 建立DataBase

1    public abstract class DataBase
2 {
3 protected DataContext DB;
4 public DataBase()
5 {
6 this.DB = new LINQ.DataClasses1DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["XXB"].ToString());
7 }
8 public virtual IQueryable<TEntity> GetModel<TEntity>() where TEntity : class
9 {
10 return this.DB.GetTable<TEntity>();
11 }
12
13

2 建立一个User_InfoRepository

1   public class User_InfoRepository : DataBase
2 {
3 /// <summary>
4 /// 需要把Join的表关系写在这里
5 /// </summary>
6 /// <returns></returns>
7 public IQueryable<User_Info> GetDetailModel()
8 {
9 var linq = from data1 in base.GetModel<User_Info>()
10 join data2 in base.GetModel<User_Profile>() on data1.UserID equals data2.UserID
11 select data1;
12 return linq;
13 }
14

3 建立一个User_ProfileRepository

1   public class User_ProfileRespository : DataBase
2 {
3

4 建立一个调用方法

  如果是使用User_InfoRepository对象与User_ProfileRepository直接在外边做join时,它就会抛异常了,这是正常的,当然,如果它是正确的,那我们的

今天要说的第三种方案也是没有意义了,呵呵。

错误的作用(看着挻好,但它是一种“查询包含对不同数据上下文上所定义项的引用”的)

1        var linq2 = from data1 in new User_InfoRepository().GetModel<User_Info>()
2 join data2 in new User_ProfileRespository().GetModel<User_Profile>() on data1.UserID equals data2.UserID
3 select data1;
4 linq2.Take(10).ToList().ForEach(i => Console.WriteLine(i.UserName));

正确的(有点太局限了,所以,以后还是用第2种方案吧,呵呵)

1        var linq = from data1 in new User_InfoRepository().GetDetailModel()
2 select data1;
3 linq.Take(10).ToList().ForEach(i => Console.WriteLine(i.UserName));

事实上,在linq这个新世界里,有着很多我们不清晰,而且微软自己也不太清楚的概念,这需要我们自己去探讨,呵呵。

作者:仓储大叔,张占岭,
荣誉:微软MVP

举报

相关推荐

0 条评论