在 LINQ 查询中使用计算值/标量值
我在 Telerik OpenAccess 生成的数据模型上使用 LINQ,以设置搜索查询并获取结果。这一切都运行得很好,并且代码看起来非常漂亮。 但现在我需要添加一件事,但我不知道如何添加。 我选择的产品对于每个客户应该有不同的价格。价格取决于另外 2 个 SQL 表中的一些其他值。现在我在 SQL 标量函数中进行价格计算,但我不确定如何将其与 LINQ 结合使用。
我的目标是检索一次数据库往返中的所有数据,并能够对这个计算出的价格列进行排序。
现在我有这样的东西:
var products = (from p in Products select p);
if(searchOption)
products = products.Where(product => product.Name.Contains(searchOption));
products = products.OrderByDescending(product => product.Name);
products = products.Skip(pageNr * pageSize).Take(pageSize);
我当然可以使用我的 Product 类的所有属性,但我希望能够使用新的虚拟/计算属性,比如说:Product.CalculatedPrice。
我有一种感觉,它应该看起来有点像这样。
(from p in Products
select new {
productId = p.ProductId,
name = p.Name,
calculatedPrice = CalculatedValueFromStoredProcedure/OrScalarFunction(p.ProductId, loggedInCustomerId)
});
最好的问候,泰斯
I'm using LINQ on a Telerik OpenAccess generated data model, to setup a search query and get the results. This all works very well and the code looks very nice.
But now i need to add one more thing, and i'm not sure how to.
The products i'm selecting should have a different price for each customer. The price depends on some other values in 2 other SQL tables. Right now i have the price calculation in a SQL scalar function, but i'm not sure on how to use that in combination with my LINQ.
My goal is to retrieve all data in one database roundtrip, and to be able to sort on this calculated price column as well.
Right now i have something like:
var products = (from p in Products select p);
if(searchOption)
products = products.Where(product => product.Name.Contains(searchOption));
products = products.OrderByDescending(product => product.Name);
products = products.Skip(pageNr * pageSize).Take(pageSize);
I can, of course, use all properties of my Product class, but i want to be able to use a new virtual/calculated property, let say: Product.CalculatedPrice as well.
I have a feeling it should look a bit like this.
(from p in Products
select new {
productId = p.ProductId,
name = p.Name,
calculatedPrice = CalculatedValueFromStoredProcedure/OrScalarFunction(p.ProductId, loggedInCustomerId)
});
Best Regards, Tys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.Select() 允许您创建动态类型,在其中您可以使用计算出的价格或在您的初始行中扩展产品
:
.Select() allows you to create a dynamic type, in which you can extend the product with the calculated price
or in your initial line:
经过更多研究后,我发现我想要做的事情与 Telerik OpenAccess ORM 结合起来是不可能的!因此,我创建了一个解决方法,可以预先计算我需要的值,将它们放入表中,并将我的选择与该表的内容连接起来。
目前,这是我找到的最好的解决方案。
After doing some more research i've found out that what i want to do is NOT possible in combination with the Telerik OpenAccess ORM! So i've created a workaround that pre-calculates the values i need, put them in a table and join my selection with the contents of that table.
For now, that's the best possible solution i've found.