如何将linq中的值解析为实体?

时间:2012-09-06 15:56:39

标签: c# entity-framework types

我想做这样的事情:

var apps = from app in context.Apps
    where (platform == AppPlatform.All ||
    (app.Platform == sPlatform && new Version(app.PlatformVersion) <= version))&&
    (availability == AppAvailability.All || app.Availability == sAvailability)
    select app;
return apps.ToList();

new Version(app.PlatformVersion) <= version))导致错误:Only parameterless constructors and initializers are supported in LINQ to Entities.

基本上我需要的是让我的实体模型将app.PlatformVersion解析为一个新的Version()对象,而不是字符串,但我显然无法在我的linq-to-entity中执行此操作。我可以在实体模型级别执行此操作吗?我还有其他字段(字符串),我也想解析为类型(比如将字符串解析为Enum)。我怎么做到这一点?

1 个答案:

答案 0 :(得分:1)

因为EF尝试将Linq查询转换为SQL,并且无法转换Version方法。因此,您可以先查询其他条件并将其存储在内存中,然后使用复杂的Linq查询从内存中对象进行查询。

从技术上讲,你可以做到这一点,(你绝对可以在性能方面做得更好)

var apps_temp = from app in context.Apps.All().ToList();

//this query will not be translated to SQL.
var apps = from app in apps_temp
    where (platform == AppPlatform.All ||
    (app.Platform == sPlatform && new Version(app.PlatformVersion) <= version))&&
    (availability == AppAvailability.All || app.Availability == sAvailability)
    select app;


return apps.ToList();