LinqPad的使用,LeftJoin遇到的问题, 连接数据库初始化问题

1.EF CodeFirst  ,查询数据库。

写连接表的类,如果不想自己写,可以用实体数据模型edmx,添加表进去,自动生成数据类,再考到CodeFirst的工程。

类建好,连接数据库。

初始化的地方改成null,可以读取现有数据库数据

如果用DropCreateDatabaseIfModelChanges,在WebMVC中,可以读取数据,表不存在会自动创建新表。但是在WCF工程中,读取不到现有表数据,也不能创建新表。

public topviewxpDb():base("topviewxpConnection")
        {
            Database.SetInitializer<topviewxpDb>(null);
            //DropCreateDatabaseAlways   //数据模型发生变化是重新创建数据库
            //DropCreateDatabaseIfModelChanges

        }

2.LeftJoin问题:

    原有查询数据库SQL语句:

select t1.Items, t1.Class, t1.Name, isnull(t2.TypeCode,0) as nType from t_SetModel t1 left join t_Template_TypeProperty t2 on (t1.ID+'_前面板_0.png') = t2.FrontElevation where t1.Items <> '' and t1.Class <> '' order by t1.Items, t1.Class, nType

    改成Linq语句:

     List<t_SetModel> modelList = db.t_SetModels.ToList();

     List<t_Template_TypeProperty> typeList = db.t_TypeProperties.ToList();

     var list = from model in modelList
                           join type in typeList on (model.ID + "_前面板_0.png") equals type.FrontElevation into cls
                           from c in cls.DefaultIfEmpty()
                           where model.Items != "" && model.Class != ""
                           orderby model.Items, model.Class
                           select new
                           {
                               Item = model.Items,
                               Class = model.Class,
                               Name = model.Name,

                               nType = c == null ? 0 : c.TypeCode 

                                 //开始想着判断c.TypeCode,后面通过linqPad调试,发现leftjoin情况下,C就是空的。

                           };

    LeftJoin在某些情况下,会出现一些数据为空的情况。

    LeftJoin跟正常Join区别:Join之后加入一个临时表,在新表后加.DefaultIfEmpty()

    from x in XTable

    join y in YTable on x.x equale y.y into newTable

    from newValue in newTable.DefaultIfEmpty()

    select new

     {

            X1=x.x;

            Y1=newValue==null?"":newValue.y

      }

       //Todo:嵌套的LeftJon查询


3. LinqPad的使用

    


猜你喜欢

转载自blog.csdn.net/Witness_K/article/details/80829240
今日推荐