In the era of handwriting SQL, if you want to randomly retrieve several pieces of data from the sqlserver database, you can use order by newid () to easily implement multi-table queries, or you can use select * From, B Where. id = B. ID, but how do I implement these functions in LINQ to SQL?
Key points:
1. random sorting: Select (D => New {newid = new GUID ()}) can be used ()}). orderby (D => D. newid) achieves the effect of order by newid ()
2. Multi-Table query
From a in tablea
From B in tableb
Where a. ID = B. ID
In addition, using LINQ to XML can also easily save the query results as XML (this is indeed much newer than the traditional XML method)
DetailsCodeRefer to my example in a project (the function is to randomly retrieve 10 product videos and generate xml for the player to call)
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 );
// Use LINQ to XML to generate 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 ();
}