简体   繁体   English

Linq to sql高效解决方案

[英]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. 最近开始使用linq to sql,我不确定什么是查询数据库并仅获得我所需的最有效方法。

  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. 我认为db.GetTable从表中获取所有记录,但我只想从db中获取一条记录,有没有办法做到这一点。

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. 注意: linq查询将始终获得一条记录“某物”是产品名称,因此对于每个产品名称,将有一个比率。

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. 我还认为,最佳做法是将数据库上下文包含在using语句内。 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. get表在实际执行之前不会获取所有记录。

Tables in a relational database are represented as Table collections (which implements interfaces such as IQueryable and IEnumerable). 关系数据库中的表表示为表集合(实现了IQueryable和IEnumerable之类的接口)。 DataContext has a method called GetTable<>(); DataContext有一个称为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 . GetTable()的类型参数标识数据库中的表

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. Single()如果你的ResultSet包含0或一个以上的元素......会抛出异常First()FirstOrDefault()似乎是更适合你的情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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