Sql 在EntityCollection中使用foor循环的替代方法?
我有以下数据库结构,其中产品具有默认价格,如果为给定rateID找到该产品的行,则可以覆盖该默认价格,如果该行不存在,则返回默认价格。Prices是EntityCollection,所以它不实现IQueryable接口,我希望在我的模型中有这个逻辑,当前的实现可以工作,但是使用forloop似乎不是很理想,关于如何改进代码有什么想法吗 桌子 产品 速度 价格 我的产品型号:Sql 在EntityCollection中使用foor循环的替代方法?,sql,database,linq,entity-framework,linq-to-sql,Sql,Database,Linq,Entity Framework,Linq To Sql,我有以下数据库结构,其中产品具有默认价格,如果为给定rateID找到该产品的行,则可以覆盖该默认价格,如果该行不存在,则返回默认价格。Prices是EntityCollection,所以它不实现IQueryable接口,我希望在我的模型中有这个逻辑,当前的实现可以工作,但是使用forloop似乎不是很理想,关于如何改进代码有什么想法吗 桌子 产品 速度 价格 我的产品型号: public partial class Product { public decimal GetPrice(Gu
public partial class Product
{
public decimal GetPrice(Guid rateId) {
foreach (Price p in Prices)
if (p.Rate.RateId == rateId)
return p.NewPrice;
return DefaultPrice;
}
}
我的控制器:
public ActionResult Prices() {
var products = storeDB.Products
.Include("Family")
.Include("Prices")
.OrderBy(product => product.Name)
.ToList();
var viewModel = new ProductPricesViewModel {
Products = products.ToList(),
Rates = storeDB.Rates.ToList()
};
return View(viewModel);
}
试一试
备选方案:
return Prices.Where ( p => p.Rate.RateId == rateId ).Select (p.NewPrice).DefaultIfEmpty (DefaultPrice);
看
public partial class Product
{
public decimal GetPrice(Guid rateId) {
foreach (Price p in Prices)
if (p.Rate.RateId == rateId)
return p.NewPrice;
return DefaultPrice;
}
}
public ActionResult Prices() {
var products = storeDB.Products
.Include("Family")
.Include("Prices")
.OrderBy(product => product.Name)
.ToList();
var viewModel = new ProductPricesViewModel {
Products = products.ToList(),
Rates = storeDB.Rates.ToList()
};
return View(viewModel);
}
return (from p in Prices where p.Rate.RateId == rateId select p.NewPrice).DefaultIfEmpty (DefaultPrice);
return Prices.Where ( p => p.Rate.RateId == rateId ).Select (p.NewPrice).DefaultIfEmpty (DefaultPrice);