【问题标题】:Entity framework code first convert between class boolean and column integer实体框架代码首先在类布尔值和列整数之间转换
【发布时间】:2013-03-07 09:39:06
【问题描述】:

我正在使用Entity Framework 5 code first。我的表有一个名为Active 的列,它的数据类型是int 类型。 Active 中存储的值为01null

我有一个类需要映射到该表。

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 为假,1 为真,null 为空,任何其他数字为假。

更新

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

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

【问题讨论】:

  • 你试过 HasColumnType("int") 吗?遇到同样的问题,我在SQL server中将列类型设置为bit。
  • 见我上面的更新。是的,我也想将它设置为 bit,但它不是我的服务器,所以我不能去更改表结构 :)

标签: entity-framework entity-framework-4 ado.net entity-framework-4.1 entity-framework-5


【解决方案1】:

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

我删除了这一行:

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

可能有更好的方法,但目前这对我有用。如果有人可以做得更好,请继续:)

【讨论】:

  • 这里的重点是:IsActive 从 sql server 是未知的,所以如果你在 where 中使用这个字段进行查询,你必须获取客户端的所有表行。顺便说一句,您的上下文中有 Ignore(x => x.IsActive) 吗?如果没有,映射是否运行 UnExceptionnaly ?
  • 不,我没有忽略它。这种方式也不例外。
【解决方案2】:
 SELECT   CONVERT(A.bitcolumn as bit) as bitout

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多