将我的值类型转换为可空值 [英] Convert my value type to nullable equivalent
问题描述
我有一个临时报告系统;我没有查询源类型或必填字段的编译时知识.我可以在运行时使用System.Linq.Expressions.Expression
工厂方法编写表达式树,并使用反射来调用LINQ方法,但是Dynamic LINQ是一个更简单的解决方案.
I have an ad-hoc reporting system; I have no compile-time knowledge of the source type of queries or of the required fields. I could write expression trees at runtime using the System.Linq.Expressions.Expression
factory methods, and invoke LINQ methods using reflection, but Dynamic LINQ is a simpler solution.
报告系统应允许返回LEFT JOIN结果的查询.连接表中的某些字段在数据库中为NOT NULL
;但是由于这是LEFT JOIN
,因此对于某些记录,这些字段将包含NULL
. EF6生成的表达式依赖于此,因为该表达式投影为不可为null的值类型.
The reporting system is to allow for queries which returns the result of a LEFT JOIN. There are fields in the joined table which are NOT NULL
in the database; but because this is a LEFT JOIN
, those fields will contain NULL
for certain records. The EF6-generated expression falls on this, because the expression projects to a non-nullable value type.
如果我是在编译时LINQ上执行此操作,则将显式转换为可空类型:
If I was doing this in compile-time LINQ, I would explicitly cast to the nullable type:
enum Color { Red, Green, Blue }
// using System;
// using static System.Linq.Enumerable;
// using System.Linq;
var range = Range(0, 3).Select(x => (Color)x).AsQueryable();
var qry = range.Select(x => (Color?)x);
动态LINQ支持显式转换:
Dynamic LINQ supports explicit conversions:
// using static System.Linq.Dynamic.Core
var qry1 = range.Select("int?(it)");
,但仅特定类型的集合可以在查询中引用.如果我尝试在查询中使用Color
:
but only a specific set of types can be referenced in the query. If I try to use Color
in the query:
var qry2 = range.Select("Color(it)");
我收到以下错误:
颜色"类型中不存在适用的方法颜色"
No applicable method 'Color' exists in type 'Color'
,如果我尝试显式转换为Color?
:
and if I try to explicitly cast to Color?
:
var qry3 = range.Select("Color?(it)");
我得到:
未找到所需的值'Color'.
Requested value 'Color' was not found.
如何使用Dynamic LINQ库执行此操作?
推荐答案
动态LINQ提供了一种Cast
方法,该方法可以按如下方式使用:
Dynamic LINQ provides a Cast
method which can be used as follows:
var range = Enumerable.Range(0,3).Select(x => (Color)x).AsQueryable();
var castDynamic = range.Cast(typeof(Color?)).ToDynamicArray();
castDynamic.Dump();
您还可以传递带有输出类型名称的字符串.请注意,对于可为空的类型,您需要该类型的全名:
You can also pass a string with the name of the output type. Note that for nullable types, you need the full name of the type:
string s = typeof(Color?).FullName;
s.Dump();
var castDynamicFromString = range.Cast(s);
castDynamicFromString.Dump();
Cast
也可以在动态LINQ字符串表达式中使用,可以将Type
对象作为参数传递,也可以直接使用名称:
Cast
can also be used within the Dynamic LINQ string expression, either passing in a Type
object as a parameter, or by using the name directly:
var castInSelect = range.Select($@"Cast(""{s}""").ToDynamicArray();
castInSelect.Dump();
在LINQPad中输出:
Output in LINQPad:
这篇关于将我的值类型转换为可空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!