Entity framework 实体框架代码首先在类布尔值和列整数之间转换

Entity framework 实体框架代码首先在类布尔值和列整数之间转换,entity-framework,entity-framework-4,ado.net,entity-framework-4.1,entity-framework-5,Entity Framework,Entity Framework 4,Ado.net,Entity Framework 4.1,Entity Framework 5,我首先使用的是实体框架5代码。我的表有一个名为Active的列,其数据类型为int。存储在Active中的值有0、1和null 我有一个类需要映射到此表 public class CommandExecutionServer : IEntity { public int Id { get; set; } public bool? IsActive { get; set; } } 这是我的配置文件。我试图将类中的布尔属性映射到数据库中的整数字段 class CommandE

我首先使用的是
实体框架5代码
。我的表有一个名为
Active
的列,其数据类型为
int
。存储在Active中的值有
0
1
null

我有一个类需要映射到此表

public class CommandExecutionServer : IEntity
{
     public int Id { get; set; }

     public bool? IsActive { get; set; }
}
这是我的配置文件。我试图将类中的布尔属性映射到数据库中的整数字段

class CommandExecutionServerConfiguration : EntityTypeConfiguration<CommandExecutionServer>
{
     internal CommandExecutionServerConfiguration()
     {
          this.ToTable("tblCommandExecutionServers");
          this.Property(x => x.IsActive).HasColumnName("Active").HasColumnType("bit");
     }
}
我尝试添加
.hascollantype(“bit”)
,并认为这可能会解决我的问题。我该怎么做?理想情况下,我希望0为false,1为true,null为null,任何其他数字为false

更新

如果我将上述内容更改为:

this.Property(x => x.IsActive).HasColumnName("Active").HasColumnType("int");
…然后我得到以下错误:

Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=True,DefaultValue=]' of member 'IsActive' in type 'MyProject.Infrastructure.EntityFramework.CommandExecutionServer' is not compatible with 'SqlServer.int[Nullable=True,DefaultValue=]' of member 'Active' in type 'CodeFirstDatabaseSchema.CommandExecutionServer'.

我尝试了以下方法,因为我不知道Entity Framework是否可以为我处理转换

我删除了这一行:

this.Property(x => x.IsActive).HasColumnName("Active").HasColumnType("int");
然后,我向我的
CommandExecutionServer类添加了一个属性:

public class CommandExecutionServer : IEntity
{
     public int Id { get; set; }

     public int? Active { get; set; }

     public bool IsActive
     {
          get
          {
               return (Active == 1) ? true : false;
          }
     }
}
也许有更好的办法,但这对我来说暂时有效。如果有人能做得更好,请继续:)


ado.net将位转换为布尔值。因此,只需在t-sql中的select语句中将整数转换为一个位。

您尝试过HasColumnType(“int”)吗?由于同样的问题,我在SQL server中将列类型设置为bit。请参阅上面的更新。是的,我也想将其设置为bit,但它不是我的服务器,因此我无法更改表结构:)这里的要点是:IsActive在sql server中是未知的,因此如果在where中使用此字段进行查询,则必须从客户端获取所有表行。顺便说一句,您的上下文中是否有忽略(x=>x.IsActive)选项?如果不是,映射是否正常运行?不,我没有将其作为忽略。这样也不例外。
public class CommandExecutionServer : IEntity
{
     public int Id { get; set; }

     public int? Active { get; set; }

     public bool IsActive
     {
          get
          {
               return (Active == 1) ? true : false;
          }
     }
}
 SELECT   CONVERT(A.bitcolumn as bit) as bitout