在手写sql的年代,如果想从sqlserver数据库随机取几条数据,可以利用order by NewId()轻松实现,要实现多表查询也可以用select * from A,B Where A.ID=B.ID做到,但这些功能到了linq to sql中如何实现呢?
关键点:
1.随机排序问题:可以用 Select(d=> new {NewId=new Guid()}).OrderBy(d=>d.NewId)达到order by NewId()的效果
2.多表查询
from a in TableA
from b in TableB
where a.ID == b.ID
另外利用linq to xml还可以轻易将查询出来的结果保存成xml(这一点比传统xml的方法确实要新颖很多)
详细代码可参考我在一个项目中的示例(功能为随机取机10条产品视频的记录,并生成xml供播放器调用)
using (DBDataContext db = new DBDataContext(Database.ConnectionString))
{
var q = db.T_Shops.Where(s => s.F_ID == new Guid("00000000-0000-0000-0000-000000000001")).Select(s => new { s.F_AutoID }).First();
string _ShopAutoId = q.F_AutoID.ToString();
var query = (from v in db.V_ProductVideos
from pv in db.V_ProductTV
where v.F_ShopID == new Guid("00000000-0000-0000-0000-000000000001") &&
v.F_ProductID == pv.F_ID &&
pv.F_Status == 1 &&
pv.F_isShow == 1 &&
v.F_Status == 1 &&
v.F_isShow == 1 &&
v.F_ProductStatus == 1
select new
{
v.F_VideoS,
v.F_VideoP,
v.F_VideoW,
v.F_VideoL,
v.F_ClsAutoID,
v.F_ProductName,
v.F_ProductAutoID,
NewId = Utils.NewComb()
}
).OrderBy(p => p.NewId).Take(10);
//利用linq to xml生成xml
XDocument doc = new XDocument(
new XElement("flvLists", from d in query
select (
new XElement(
"item",
new XAttribute("title_p", d.F_VideoP),
new XAttribute("title_s", d.F_VideoS),
new XAttribute("name", Utils.NoHtml(d.F_ProductName, 500)),
new XAttribute("link", "http://www.cntvs.com/product/" + d.F_ClsAutoID.ToString() + "/" + _ShopAutoId + "/" + d.F_ProductAutoID)
))));
doc.Save(Server.MapPath("~/upload/xml/tvvideo.xml"));
db.Connection.Close();
}
{
var q = db.T_Shops.Where(s => s.F_ID == new Guid("00000000-0000-0000-0000-000000000001")).Select(s => new { s.F_AutoID }).First();
string _ShopAutoId = q.F_AutoID.ToString();
var query = (from v in db.V_ProductVideos
from pv in db.V_ProductTV
where v.F_ShopID == new Guid("00000000-0000-0000-0000-000000000001") &&
v.F_ProductID == pv.F_ID &&
pv.F_Status == 1 &&
pv.F_isShow == 1 &&
v.F_Status == 1 &&
v.F_isShow == 1 &&
v.F_ProductStatus == 1
select new
{
v.F_VideoS,
v.F_VideoP,
v.F_VideoW,
v.F_VideoL,
v.F_ClsAutoID,
v.F_ProductName,
v.F_ProductAutoID,
NewId = Utils.NewComb()
}
).OrderBy(p => p.NewId).Take(10);
//利用linq to xml生成xml
XDocument doc = new XDocument(
new XElement("flvLists", from d in query
select (
new XElement(
"item",
new XAttribute("title_p", d.F_VideoP),
new XAttribute("title_s", d.F_VideoS),
new XAttribute("name", Utils.NoHtml(d.F_ProductName, 500)),
new XAttribute("link", "http://www.cntvs.com/product/" + d.F_ClsAutoID.ToString() + "/" + _ShopAutoId + "/" + d.F_ProductAutoID)
))));
doc.Save(Server.MapPath("~/upload/xml/tvvideo.xml"));
db.Connection.Close();
}