Reputation: 1075
Recently started with linq to sql and i am not sure what is the most efficient way to query a db and only get what i need.
DataContext db = new
DataContext(ConfigurationManager.AppSettings["myConnection"]);
Table<RatesClass> CurrencyRatestbl = db.GetTable<RatesClass>();
double Rate = 0.00;
Rate =
(from c in CurrencyRatestbl
where c.From == "something"
select Convert.ToDouble(c.Rate)).Single();
I think db.GetTable get all the records from the table but i want only get one record from db, is there a way to do it.
Note: the linq query will always get one record "something" is the product name, so for every product name there will be a single rate.
Upvotes: 0
Views: 170
Reputation: 31239
You can also do it like this:
using(DataContext db = new DataContext(ConfigurationManager.AppSettings["myConnection"]))
{
var rate=db.GetTable<RatesClass>()
.Where(a=>a.From == "something")
.Select(a=>Convert.ToDouble(a.Rate))
.SingleOrDefault();
}
I also think that it is best practice to have the database context inside a using statement. So that the connection to the database is open as long as it needs. The get table do not get all the records before is it actually executed.
Tables in a relational database are represented as Table collections (which implements interfaces such as IQueryable and IEnumerable). DataContext has a method called GetTable<>(); it represents a potential interaction with the table of view. The query is not actually executed until iteration over the result is performed. The type parameter of GetTable() identifies the table in the database.
Reference here
Upvotes: 3
Reputation: 7662
Single()
will throw an Exception if your ResultSet contains 0 or more than one elements... First()
or FirstOrDefault()
appears to be more suitable in your case.
DataContext db = new DataContext(ConfigurationManager.AppSettings["myConnection"]);
Table<RatesClass> CurrencyRatestbl = db.GetTable<RatesClass>();
double Rate = 0.00;
Rate = (from c in CurrencyRatestbl
where c.From == "something"
select Convert.ToDouble(c.Rate)).FirstOrDefault();
Upvotes: 0