ef 联合查询 理解
作者:互联网
1.情景
用到数据库联合查询时比不可少的。今天用到一个外键在表示的时候需要转换成名称。自然需要联合查询,网上一查,最多的就是下面的这段代码,真挺经典且简单。
//ef
var query2 = db.m_Dept.Join(db.m_User, a => a.ID, b => b.DeptID, (a, b) => new
{
deptname = a.DName,
u
第一次使用,不太理解 a和b 分别是啥?基本可以确定是m_Dept 和 m_User 表。那么怎么确定呢。两个变量a.ID 和 b.DeptID都是 a的。首先想象的还原一下语句吧
select a.Dnam,b.Uname from m_Dept a join m_User b on a.ID = b.DeptID
这下明白了,这关系要说吧,还真有点复杂,且不准备,就这样理解,a.ID和b.DeptID首先以m_Dept 为基础,那么 a.ID代码自己,b.DeptID代码外联的表m_User,由此条件产生的两个表a、b 分别代表m_Dept和 m_User。
2.代码
private void Add()
{
List<m_Dept> lst = new List<m_Dept>{
new m_Dept { DName = "开发", ID = "1" },
new m_Dept { DName = "测试", ID = "2" },
new m_Dept { DName = "财务", ID = "3" }
};
List<m_User> lstU = new List<m_User>{
new m_User { UName = "张三", ID = "1" , DeptID="1"},
new m_User { UName = "李四", ID = "2" , DeptID="2"},
new m_User { UName = "王五", ID = "3" , DeptID="1"}
};
using(TESTEntities db=new TESTEntities())
{
db.m_Dept.AddRange(lst);
db.m_User.AddRange(lstU);
db.SaveChanges();
}
}
private void getlist()
{
using (TESTEntities db = new TESTEntities())
{
//linq
var query = from a in db.m_Dept
join b in db.m_User
on a.ID equals b.DeptID
select new
{
deptname = a.DName,
username = b.UName
};
//ef
var query2 = db.m_Dept.Join(db.m_User, a => a.ID, b => b.DeptID, (a, b) => new
{
deptname = a.DName,
username = b.UName
});
}
}
标签:DeptID,ef,db,查询,Dept,理解,User,new,ID 来源: https://blog.csdn.net/xie__jin__cheng/article/details/120682410