我有一个成功执行的 linq 查询,返回的列之一是十进制类型,用于表示以英镑和便士为单位的价格(永远不会有任何负值)
我希望能够将英镑和便士剥离到投影的单独属性中,但是在使用诸如
之类的功能时var result= from j in context.Products
select
new{
Price = t.Price,
PricePounds = Math.Truncate(t.Price)
};
我收到一条错误消息,指出不支持 Math.truncate,因为它无法转换为存储表达式。如何从此查询中获取磅值?
最佳答案
如果在那之后您不需要在数据库中做任何其他事情,最简单的方法就是在客户端执行截断:
var query = context.Products
.AsEnumerable() // Everything from here is LINQ to Objects
.Select(p => new {
p.Price,
PricePounds = Math.Truncate(p.Price)
});
请注意,您可能还想转换为 int
- 并且 可能已经在 EF 中得到支持。
编辑:如评论中所述,您可能希望先执行投影,例如
var query = context.Products
.Select(p => new { p.Price, p.SomethingElse })
.AsEnumerable() // Everything from here is LINQ to Objects
.Select(p => new {
p.Price,
PricePounds = Math.Truncate(p.Price),
p.SomethingElse
});
(例如,SomethingElse
是您感兴趣的另一个属性 - 我怀疑您只想要价格。)
这将避免在您只需要几个属性时获取整个实体。
关于C#仅使用linq显示小数点后的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12267435/