【发布时间】:2018-11-21 07:24:07
【问题描述】:
当我想对数据库实体做一些验证的时候,我可以想到两种方法:
1:检索字段值,然后在应用程序中进行计算:
if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate).Single() <= DateTime.Now)
2:在查询中进行计算(在 'Select()' 方法中),然后检索结果:
if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate <= DateTime.Now).Single())
【问题讨论】:
-
如果你只是用一些数据做一个基准测试会不会快很多?然后你就会知道哪一个更好,性能明智
-
如果您的
couponId是主键(好吧,根据您的 where->select->single - 它是),而不是.Where(c=> c.Id == couponId)您可以使用Coupons.Find(couponId).ExpirationDate <= DateTime.Now。 -
@SeM Find 方法从数据库中检索整行并实际上杀死了性能。
-
@AmirHosseinAhmadi 这取决于您的行是否存在于缓存中。
标签: c# sql entity-framework linq-to-sql linq-to-entities