在EF 4.x中处理将0/1转换为False / True的最简单方法是什么?

存储的Proc返回一列,其值为0或1,而不转换为BIT。 在我的POCO中,如果我将该字段声明为

public bool MyColumn {get; set;} 

我收到此错误:

 The specified cast from a materialized 'System.Int32' type to the 'System.Boolean' type is not valid. 

这实际上是有意义的,因为EF将返回值识别为整数。

我想知道是否有任何简单的方法(添加注释或使用流畅的api可能)在场景后面的映射中自动将0/1转换为False / True而不触及Proc?

提前致谢!

你可以做的是让另一个属性来表示布尔表示。 使用NotMapped属性装饰它,以便EF不会将其视为Mapping。 Do和If条件并根据Other属性的值返回true /false

 public Class Customer { [NotMapped] public bool MyColumnBool { get { return (MyColumn ==1); } } public int MyColumn {get; set;} // other properties } 

另一个选择是从存储过程返回一个BIT,这样你就不需要在C#端投射任何东西或使用任何奇怪的装饰。 这意味着,您可以将整数值转换为T-SQL中的BIT,如下所示:

 select col1, col2, CONVERT(BIT, CASE WHEN col3 IS NULL THEN 0 ELSE 1 END) as colWithBit FROM table1 

使用System.Convert.ToBoolean(int)