gpt4 book ai didi

entity-framework - Entity Framework 代码首先在类 bool 值和列整数之间进行转换

转载 作者:行者123 更新时间:2023-12-01 03:58:34 25 4
gpt4 key购买 nike

我正在使用 Entity Framework 5 code first .我的表有一列名为 Active并且它的数据类型是类型 int .存储在 Active 中的值为 0 , 1null .

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

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

public bool? IsActive { get; set; }
}

这是我的配置文件。我试图将我的类中的 bool 属性映射到数据库中的整数字段。
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'.

最佳答案

我尝试了以下操作,因为我不知道 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;
}
}
}

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

关于entity-framework - Entity Framework 代码首先在类 bool 值和列整数之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15267666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com