日期:2014-05-17  浏览次数:20556 次

关于MVC使用LINQ数据模型自动导入外键关系的效能问题
MVC新入门,使用linq模型直接导入数据表后,外键关系也自动建立起来。我只想返回一两个表的关系,结果追踪发现方法会自动把所有关联表数据全部导入到对象中,如果对应数据多的话,对效能是不是有很大影响?如何解决
比如
C# code
return db.aspnet_User.SingleOrDefault(d => d.UserName == UserName)

我预期的目的是只返回这个表的数据,结果追踪发现方法会把其他表的关联数据也导进来
之前还傻乎乎的这么写
C# code

        public FullUserModelList FindAllUsers()
        {
            var fullUserModel = from aU in db.aspnet_User
                                join aMs in db.aspnet_Membership on aU.UserId equals aMs.UserId
                                join ue in db.M_UserExpand on aU.UserId equals ue.UserID
                                join aUIR in db.aspnet_UsersInRoles on aMs.UserId equals aUIR.UserId
                                join aR in db.aspnet_Roles on aUIR.RoleId equals aR.RoleId
                                orderby aMs.CreateDate
                                select new FullUserModel
                                {
                                    aspnet_User = aU,
                                    aspnet_Membership = aMs,
                                    aspnet_UsersInRoles = aUIR,
                                    aspnet_Roles = aR,
                                    M_UserExpand = ue
                                };
            return new FullUserModelList { FullUserModel = fullUserModel };
        }



------解决方案--------------------
在Linq中join连接不是左连接

左连接写法:
 
C# code
var b = new Modular.SparePartsModular();
                    var re = b.GetALL();//查询出库存上下限
                    var dt = ifs.getPorts(out _total, page, rows, no, desc, null).Tables[0];//ERP备件信息
                    var ps = from d in dt.AsEnumerable()
                             join r in re on d.Field<string>("part_no") equals r.IFSID into joinedEmpDept
                             from dept in joinedEmpDept.DefaultIfEmpty()
                             select new
                                        {
                                            IFSID = d.Field<string>("part_no"),
                                            Description = d.Field<string>("Description"),
                                            Num = d.Field<decimal>("count_variance"),
                                            Unit = d.Field<string>("unit_meas"),
                                            IN_TRANSIT = d.Field<decimal>("IN_TRANSIT"),
                                            Price = d.Field<decimal>("price"),
                                            MAX = dept != null ? dept.MAX : 0,
                                            MIN = dept != null ? dept.MIN : 0,
                                            interval = d.Field<decimal>("count_variance") > (dept != null ? dept.MIN : 0) ? 1 : 0//1安全,0不安全
                                        };