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

人气:678 发布:2022-10-16 标签: entity-framework ado.net entity-framework-4 entity-framework-5 entity-framework-4.1

问题描述

我首先使用 Entity Framework 5 代码.我的表有一个名为 Active 的列,它的数据类型是 int 类型.存储在 Active 中的值是 01null.

I am using Entity Framework 5 code first. My table has a column called Active and its datatype is of type int. The values that are stored in Active are 0, 1 and null.

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

I have a class that I need to map to this table.

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

     public bool? IsActive { get; set; }
}

这是我的配置文件.我正在尝试将我的类中的布尔属性映射到数据库中的整数字段.

Here is my configuration file. I am trying to map my boolean property in my class to the integer field in the database.

class CommandExecutionServerConfiguration : EntityTypeConfiguration<CommandExecutionServer>
{
     internal CommandExecutionServerConfiguration()
     {
          this.ToTable("tblCommandExecutionServers");
          this.Property(x => x.IsActive).HasColumnName("Active").HasColumnType("bit");
     }
}

这不是很好.我得到的错误是:

This is not working well. The error that I am getting is:

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 为空,任何其他数字为假.

I tried adding .HasColumnType("bit") and thought that it might take of my problem. How do I do this? Ideally I would like 0 to be false, 1 to true, null to be null, and any other number to false.

更新

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

If I change the above to:

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

...然后我收到以下错误:

...then I get the following error:

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 是否可以为我处理转换.

I tried the following because I do not know if Entity Framework can handle the conversion for me.

我删除了这一行:

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

然后我向我的 CommandExecutionServer 类添加了一个属性:

I then added a property to my 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;
          }
     }
}

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

There might be a better way but this works for me for now. If any one can better this then please go ahead :)

271