Linq中使用Left Join
use Test
Create table Student(
ID int identity(1,1) primary key,
[Name] nvarchar(50) not null
) Create Table Book(
ID int identity(1,1) primary key,
[Name] nvarchar(50)not null,
StudentID int not null
) insert into Student values('张三')
insert into Student values('李四')
insert into Student values('王五')
select * from student --张三借的书
insert into Book values('红楼',1)
insert into Book values('大话红楼',1) --李四借的书
insert into Book values('三国',2) --王五没借书 --一本错误的记录
insert into Book values('错误时怎样练成的',111) --左连接
select s.name,b.name from student as s
left join Book as b on s.id=b.studentid --右连接
select s.name,b.name from student as s
right join Book as b on s.id=b.studentid
要用Linq实现左连接,写法如下
DataClasses1DataContext db = new DataClasses1DataContext();
var leftJoinSql = from student in db.Student
join book in db.Book on student.ID equals book.StudentID into temp
from tt in temp.DefaultIfEmpty()
select new
{
sname= student.Name,
bname = tt==null?"":tt.Name//这里主要第二个集合有可能为空。需要判断
};
用Linq实现右连接,写法如下
DataClasses1DataContext db=new DataClasses1DataContext();
var rightJoinSql = from book in db.Book
join stu in db.Student on book.StudentID equals stu.ID into joinTemp
from tmp in joinTemp.DefaultIfEmpty()
select new {
sname=tmp==null?"":tmp.Name,
bname=book.Name };
使用LINQ联合查询多表结果集的返回
首先,我们先来了解一些知识点。
.匿名类型的传递
static void Main(string[] args)
{
var User = GetAnonymous().Cast(new { UserName = "", LastLoginIp = "" });
Console.Write(User.UserName);
}
static object GetAnonymous()
{
var User = new { UserName = "yaosansi", LastLoginIp = "127.0.0.1" };
return User;
}
当我们定义一个匿名类型,只能通过object类型传递,传递后编译器将无法获悉匿名类型的实际类型。
这行可以通过Cast扩展方法来进行强制转换。以下是Cast方法的原型。
public static T Cast<T>(this object o, T t)
{
return (T)o;
}
.如何生成匿名类型的List?
var User = GetAnonymous().Cast(new { UserName = "", LastLoginIp = "" });
var list = new List<???>();
原理和上面一致。
var User = new { UserName = "yaosansi", LastLoginIp = "127.0.0.1" };
var list = User.MakeList();
list.Add(User);
Console.Write(list[].UserName);
我们再来看看MakeList()方法:
public static List<T> MakeList<T>(this T t)
{
return new List<T>();
}
当然,你可能想到上面的方法还不够完美,需要在List中Add一个User,于是有了下面的方法:
public static List<T> MakeList<T>(this T t,params T[] items)
{
return new List<T>(items);
}
这时调用的时候可以写成:
var User = new { UserName = "yaosansi", LastLoginIp = "127.0.0.1" };
var list = User.MakeList(User);
Console.Write(list[].UserName);
这回我们切入正题,来了解一下LINQ中是怎样多表查询的。
var q =
from p in db.Products
where p.Supplier.Country == "USA" && p.UnitsInStock ==
select p;
更多内容,请参考:博客园 - 李永京- LINQ体验()——LINQ to SQL语句之Join和Order By
以上的查询是两个有关系的表,并且返回的只是一个表的内容,
这种情况下可以在数据层中返回强类型的List。如:
public List<Products> SelectProducts()
{
var q =
from p in db.Products
where p.Supplier.Country == "USA" && p.UnitsInStock ==
select p;
return q.ToList<Products>;
}
如果返回的结果集是两个以上表的时候,那该如何传递呢?
聪明的你一定想到了,如果返回的是单行数据的结果集就可以我们前面提到的
使用 匿名类型的传递 得到我们需要的结果.
public object SelectProducts()
{
var q =
from p in db.Products
where p.Supplier.Country == "USA" && p.UnitsInStock ==
select new {p.UnitsInStock,p.Supplier.Sid};
var result = q.Single();
return result;
}
但这个前提是业务逻辑层需要知道数据层的匿名类型中的具体类型。
这样分层的意义也就不大了。这并不是我们想要的。
而且返回多行数据的结果集时用 匿名的List类型 的方法经实验也失败了。
这就意味着本文开篇的两种传递匿名类型的方法都行不通。
方法一:
自定义与返回类型相同结构的类,
public class CustomQuery
{
public uint UnitsInStock { get; set; }
public int Sid { get; set; }
}
这样在查询结果为多个表的结果集时,就可以解决了。
由于需要知道返回的匿名类型,除了不符合多层以外,还需要额外定义一个类。
但这样确时可以使用强类型返回我们所需要的结果。
方法二:
使用System.Func委托 (参考:Returning var from a method in C# 3.0)
数据层:
public IEnumerable<TProjection> GetCustomersWithOrders<TProjection>(Func<Customer, IEnumerable<Order>, TProjection> projection) {
return from customer in _customers
let customerOrders = from order in _orders
where order.CustomerID = customer.ID
select projection(customer, customerOrders);
}
业务逻辑层:
var results = GetCustomersWithOrders((customer, orders) =>
new {
Name = customer.Name,
OrderCount = orders.Count()
});
这样返回的结果在业务逻辑层里仍然是真正的匿名类型,可以直接使用了。
方法三:
使用存储过程或视图。
Linq中使用Left Join的更多相关文章
- Linq 中的 left join
Linq 中的 left join 表A User: 表B UserType: Linq: from t in UserType join u in User on t.typeId equal u. ...
- Linq中的连接(join)
http://www.cnblogs.com/scottckt/archive/2010/08/11/1797716.html Linq中连接主要有组连接.内连接.左外连接.交叉连接四种.各个用法如下 ...
- LINQ中的连接(join)用法示例
Linq中连接主要有组连接.内连接.左外连接.交叉连接四种.各个用法如下. 1. 组连接 组连接是与分组查询是一样的.即根据分组得到结果. 如下例,根据publisther分组得到结果. 使用组连接的 ...
- [转]Linq中使用Left Join
本文转自:http://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html use Test Create table Student( I ...
- Linq中使用Left Join rught join
准备一些测试数据,如下: use Test Create table Student( ID int identity(1,1) primary key, [Name] nvarchar(50) no ...
- Linq中使用Left Join 和 Right Join
原文地址:http://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html 准备一些测试数据,如下: use Test Create tab ...
- linq中如何在join中指定多个条件
public ActionResult Edit(int id) { using (DataContext db = new DataContext(ConfigurationManager.Conn ...
- Linq中的left join
left join var custs = from c in db.T_Customer join u in db.Sys_User on c.OwnerId equals u.Id into te ...
- Linq To Sql中实现Left Join与Inner Join使用Linq语法与lambda表达式
当前有两个表,sgroup与sgroupuser,两者通过gKey关联,而sgroup表记录的是组,而sgroupuser记录是组中的用户,因此在sgroupuser中不一定有数据.需要使用Left ...
随机推荐
- 专门查看阻塞和死锁情况以及引起的SQL语句,你可以创建后,直接运行之。
CREATE procedure sp_who_lock as begin declare @spid int declare @blk int declare @count int declare ...
- [置顶] 两台一级域名相同二级域名不同的服务器,怎么共享session
比如www.hongchangfirst.com和video.hongchangfirst.com两个域名,一级域名相同,二级域名不同.每个服务器运行着不同的功能模块或者不同的子系统,他们使用不同的二 ...
- jQuery实现等比例缩放大图片让大图片自适应页面布局
通常我们处理缩略图是使用后台代码(PHP..net.Java等)根据大图片生成一定尺寸的缩略图,来供前台页面调用,当然也有使用前台javascript脚本将加载后的大图强行缩放,变成所谓的缩略图,这种 ...
- effective c++ (一)
条款01:把C++看作一个语言联邦 C++是一种多重范型编程语言,一个同时支持过程(procedural),面向对象(object-oriented),函数形式(functional),泛型形式(ge ...
- jQuery 的选择器
本文来自网上转帖 1. 基础选择器 Basics 名称 说明 举例 #id 根据元素Id选择 $("divId") 选择ID为divId的元素 element 根据元素的名称选择, ...
- 【转】Android TouchEvent事件传递机制
Android TouchEvent事件传递机制 事件机制参考地址: http://www.cnblogs.com/sunzn/archive/2013/05/10/3064129.html ht ...
- js 格式化数字
http://www.jb51.net/article/61585.htm 这篇文章主要介绍了JS实现的4种数字千位符格式化方法分享,本文给出了4种千分位格式化方法并对它们的性能做了比较,需要的朋友可 ...
- 从零开始学C++之虚函数与多态(一):虚函数表指针、虚析构函数、object slicing与虚函数
一.多态 多态性是面向对象程序设计的重要特征之一. 多态性是指发出同样的消息被不同类型的对象接收时有可能导致完全不同的行为. 多态的实现: 函数重载 运算符重载 模板 虚函数 (1).静态绑定与动态绑 ...
- The Aggregate Magic Algorithms
http://aggregate.org/MAGIC/ The Aggregate Magic Algorithms There are lots of people and places that ...
- Swift学习笔记八
函数 Swift的函数语法非常独特,也提供了很高的灵活性和可读性.它可以充分表达从简单的无参数C风格函数到复杂的拥有局部变量和外部变量的OC风格的方法.参数可以有默认值,方便函数的调用.Swift中的 ...