Steps for a beginner to run very basic linq to sql query using Linqpad

烂漫一生 提交于 2019-12-03 09:00:52

问题


Trying to learn Linq using LinqPad and getting frustated with how to start on it. Let's say I want to write a C# Expression and a C# statment where I have a table in SQL server named Products and I want to pull all rows where price is greater then 50. How would yo write it?


回答1:


Let's say I want to write a C# Expression and a C# statment where I have a table in SQL server named Products and I want to pull all rows where price is greater then 50. How would yo write it?

LINQPad builds the typed DataContext for you automatically, so you don't need to instantiate anything. In C# expression mode, just type the folowing:

Products.Where(p => p.Price > 50)

and press F5. Alternatively, you might prefer to use a query expression:

from p in Products
where p.Price > 50
select p

In C# statements mode, you'll need to call the Dump() method to tell it to write out the results. You'll also need to terminate the expression with a semicolon:

Products.Where(p => p.Price > 50).Dump();

There are more examples in the samples section of LINQPad - look at the 5-minute induction.




回答2:


Just wanted to add - LINQ pad pluralizes - I did not know this and it drove me crazy for a good fifteen minutes

I was trying to select from a table called DentalApplication

    DentalApplication.Where(a=> a.PackageID > 0)

Gave me this error

    'LINQPad.User.DentalApplication' does not contain a definition for 'Where'

Changed it to

    DentalApplications.Where(a=> a.PackageID > 0)

and it worked




回答3:


var db = new MyDatabaseContext();  // Your database context.
var result = db.Products.Where(q=>q.Price > 50);

...where db represents your ORM context. Price represents your mapping to the Price field in the database. result represents the result set -- your database rows/entities.




回答4:


Check out: http://msdn.microsoft.com/en-us/library/bb397933(v=vs.90).aspx which will give you an introduction to Linq and using lambda expressions.

Then have a look at http://msdn.microsoft.com/en-us/library/bb386927.aspx which will give you the basics, but to answer your specific question:

var products = db.Products.Where(prod => prod.Price > 50);
foreach(var product in products)
{
     //do something
}


来源:https://stackoverflow.com/questions/8000031/steps-for-a-beginner-to-run-very-basic-linq-to-sql-query-using-linqpad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!