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 ...
随机推荐
- 删除qq历史签名
我们在设置新的个性签名的时候之前的签名会被记录,我们可以用手机qq删除这些历史签名,告别过去,做崭新的自己. 到需要删除的历史签名, 从右至左滑动屏幕
- 安装Sass
最近要开始用 Sass 做一些东西.先来记录一下安装过程. 1.确认本机的 Ruby 版本 2.访问网址下载 Sass 最新版本 https://rubygems.org/gems/sass 3.下载 ...
- Socket小项目的一些心得(鸣谢传智的教学视频)
Socket是一种封装了四层通信的整体抽象入口,通常也称作"套接字",这是常用的四层通信这是访问Socket的流程图,这个分为客户端和服务器端,其中服务器端有以下步骤去建立,前面的 ...
- CSS画出的各种形状图
利用CSS可以画出各种需要的图形目录[1]矩形[2]圆形[3]椭圆[4]直角三角形[5]正三角形[6]平行四边形[7]梯形[8]六角星[9]六边形[10]五角星简单图形 矩形div{ width: 1 ...
- ThinkPHP C+F方式
ThinkPHP常用C+F方法进行配置设置于缓存设置 比如常见的 C(F('smtp'),'smtp');表示获取F方法中smtp缓存,设置配置为smtp函数 C方法是ThinkPHP用于设置.获取, ...
- CentOS 安装 gcc
centos linux默认可以采用yum方式安装,则采用如下命令安装gcc编译器即可:#yum -y install gcc 系统会自动安装gcc及依赖组件 gcc ...
- Objc基础学习记录3
在学习Objective-c中, 数组 1.NSArray, 这是一个不可变的数组,不能修改和删除其中的对象,可以存储任意objective的对象指针. 不能存储int,char类型的,,需要转换为需 ...
- Merge into 使用
在进行SQL语句编写时,我们经常会遇到这样的问题:当存在记录时,就更新(Update),不存在数据时,就插入(Insert),oracle为我们提供了一种解决方法——Merge into ,具体语法如 ...
- NodeJs使用Mysql模块实现事务处理
依赖模块: 1. mysql:https://github.com/felixge/node-mysql npm install mysql --save 2. async:https://githu ...
- 升级xcode时更换appid账户
转自:http://blog.csdn.net/zhuzhihai1988/article/details/39803743 为了免下载安装Xcode,安装时使用了别人提供的Xcode.dmg安装,而 ...