3

我正在使用Entity Framework 5 code first。我的表有一个名为Active的列,其数据类型为int。存储在Active中的值是0,1null实体框架代码首先在类布尔和列整数之间转换

我有一个类,我需要映射到这张表。

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"); 
    } 
} 

这是行不通的。我正的错误是:

The 'IsActive' property on 'CommandExecutionServer' could not be set to a 'Int32' value. You must set this property to a non-null value of type 'Boolean' 

我尝试添加.HasColumnType("bit")并认为这可能需要我的问题。我该怎么做呢?理想情况下,我希望0为false,1为true,null为null,其他任何数字为false。

UPDATE

如果我改变了上面:

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'. 
+0

你试过用HasColumnType(“int”)?在同样的问题中,我将列类型设置为在SQL Server中位。 – tschmit007 2013-03-07 09:52:04

+0

看到我上面的更新。是的,我也想将它设置为位,但它不是我的服务器,所以我不能去改变表结构:) – 2013-03-07 10:15:24

回答

1

我想,因为我不以下知道实体框架是否可以为我处理转换。

我删除了这条线:

this.Property(x => x.IsActive).HasColumnName("Active").HasColumnType("int"); 

我加入一个属性来我CommandExecutionServer class

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

    public int? Active { get; set; } 

    public bool IsActive 
    { 
      get 
      { 
       return (Active == 1) ? true : false; 
      } 
    } 
} 

有可能是一个更好的方式,但这种方式更适合我现在。如果任何一个能更好地这个,那么请继续:)

+2

这里的重点是:IsActive未知从SQL服务器,所以如果你查询使用此字段在哪里,你必须得到所有的表格线客户端。顺便说一句,你有一个Ignore(x => x.IsActive)在你的上下文中吗?如果没有,映射是否运行UnExceptionnaly? – tschmit007 2013-03-07 11:33:41

+0

不,我没有它作为忽略。这种方式没有例外。 – 2013-03-07 11:56:58

1
SELECT CONVERT(A.bitcolumn as bit) as bitout 

ado.net将位转换为布尔变量。所以,只需在t-sql中的select语句中将您的整数转换为一点。

+0

太好了,谢谢 – 2017-08-19 11:52:47