LINQ 查询对于 NULL 值失败
var query = from t1 in Table1
join t2 in Table2
on new { t1.Id }
equals new { t2.Id}
select new
{
t1.Id,
t1.FirstName,
t1.MiddleName,//allows null values in the database
t1.LastName,
t1.phone //allows null values in the database
};
if(query.Count()>0)//fails here"The value for column MiddleName in table'Table1' is DBNULL"
{
}
有没有一种方法可以在 LINQ 查询中获取所有行,包括 middleName 和 Phone 的空值?
var query = from t1 in Table1
join t2 in Table2
on new { t1.Id }
equals new { t2.Id}
select new
{
t1.Id,
t1.FirstName,
t1.MiddleName,//allows null values in the database
t1.LastName,
t1.phone //allows null values in the database
};
if(query.Count()>0)//fails here"The value for column MiddleName in table'Table1' is DBNULL"
{
}
Is there a way in which I can get all the rows including null values for middleName and Phone in my LINQ query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用 linq-to-datasets,则必须手动将可为 null 的列转换为 null,因为它们在
DataRow
中的值为DBNull.Value
。在强类型数据集中,您应该能够执行以下操作:在非类型数据集中,您将调用类似
t1.IsNull("MiddleName") 的内容? null : t1["中间名"]
If you are using linq-to-datasets you must manually convert nullable columns to null because their value in
DataRow
isDBNull.Value
. In strongly typed DataSet you should be able to do something like:In untyped DataSet you will call something like
t1.IsNull("MiddleName") ? null : t1["MiddleName"]
听起来元数据与您的数据库架构不同步。似乎在为您的架构生成类时 MiddleName 不可为空,但现在可以了。如果是这种情况,如果您使用的是实体框架,则需要刷新 EDMX;如果您使用的是 LINQ to SQL,则需要刷新您的类。
It sounds like the metadata is out of sync with your DB schema. It seems as if when the classes were generated for your schema MiddleName was not nullable, but now it is. If that's the case, you need to refresh your EDMX if you're using Entity Framework or refresh your classes if you're using LINQ to SQL.
你能试一下吗
Could you please give this a shot
问题在于,新的匿名对象的属性是通过从值推断出的类型动态定义的。
在这样的行中,
创建了一个名为 MiddleName 的新属性,其类型为 t1.MiddleName 的类型。但如果 t1.MiddleName 为 null,那么类型是什么??? Null 没有类型。
为了防止任何歧义,只需
让编译器知道它无论如何都是一个字符串,即使没有提供。
The problem is that a new anonymous object has its properties defined on-the-fly with types inferred from the values.
In such a line
a new property called MiddleName is created whose type is t1.MiddleName's type. But if t1.MiddleName is null, what is the type ??? Null has no type.
To prevent any ambiguousity simply put
to let the compiler know that anyway it's a string, even if not provided.