简体   繁体   中英

Linq to sql Efficient Solution

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.

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM