Linq to entity 笔记

1.返回指定字段生成实体

            List<Product> q = db.Product.Where(a => a.ProductName == "a  ")
.Select(a => new { ProductName = a.ProductName, AddTime = a.AddTime }).ToList() // ToList() 将数据读取到内存中 然后转化成SQL
.Select(a => new Product() { ProductName = a.ProductName, AddTime = a.AddTime }).ToList();
// 生成语句
/* SELECT
1 AS [C1],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[AddTime] AS [AddTime]
FROM [dbo].[Product] AS [Extent1]
WHERE N'a' = [Extent1].[ProductName]
*/

foreach (Product p in q)
{
Console.WriteLine(p.ProductName);
}


2. 插入 :效率不行  方法有待 拓展 ,提高

                Product pro = new Product();
pro.ProductName = "I lOVER YOU";
pro.ProductPrice = 12m;
pro.AddTime = DateTime.Now;
db.AddToProduct(pro);

pro = new Product();
pro.ProductName = "I lOVER YOU";
pro.ProductPrice = 12m;
pro.AddTime = DateTime.Now;
db.AddToProduct(pro);

db.SaveChanges();
/* 生成语句
exec sp_executesql N'insert [dbo].[Product]([ProductName], [ProductPrice], [ProductDisc], [AddTime])
values (@0, @1, null, @2)
select [ProductID]
from [dbo].[Product]
where @@ROWCOUNT > 0 and [ProductID] = scope_identity()',N'@0 nvarchar(12),@1 decimal(18,0),@2 datetime',@0=N'I lOVER YOU',@1=12,@2='2012-03-15 23:05:21.860'
go
exec sp_executesql N'insert [dbo].[Product]([ProductName], [ProductPrice], [ProductDisc], [AddTime])
values (@0, @1, null, @2)
select [ProductID]
from [dbo].[Product]
where @@ROWCOUNT > 0 and [ProductID] = scope_identity()',N'@0 nvarchar(12),@1 decimal(18,0),@2 datetime',@0=N'I lOVER YOU',@1=12,@2='2012-03-15 23:05:21.860'
go

*/

 

posted @ 2012-03-15 23:13  Rhythmk  阅读(206)  评论(0编辑  收藏  举报
Rhythmk 个人笔记