c# - Entity Framework : mapping tinyint to boolean

标签 c# entity-framework mapping

Entity Framework 默认将 tinyint 映射到 byte。

我尝试将生成的基础类型更改为 bool 值,但出现编译错误

指定的成员映射无效。成员 blah 的类型 'Edm.Boolean[Nullable=False,DefaultValue=]'...

这在 4.0 中可能吗?

将 tinyint 列用作 bool 值不是我的主意。这是由另一个使用 hibernate 的团队自动完成的,显然这样做是为了与 mysql 兼容。显然 tinyint 的值比 2 多。我正在寻找一种方法来映射它,以便任何接受 1 的东西都是假的,或者任何接受 0 的东西都是真的。要么对我有用

有没有办法将某种类型的转换器插入到 EF 中?

最佳答案

如果您现有的数据库有一个 tinyint 列,您希望将其表示为 C# 类的 bool 属性,那么您可以按如下方式执行此操作:

public class Subscription
{
  public int Id { get; set; }
  public string Name { get; set; }

  // the column of your database
  public byte? autoRenew { get; set; }

  // the property you want
  [NotMapped]
  public bool Autorenew
  {
    get => autoRenew > 0;
    set { this.autoRenew = (byte)(value ? 1 : 0);  }
  }
}

显然,这假设 0 和 1 分别对应于 false 和 true。在此示例中,autoRenew 可以为 null,null 被解释为 false。

关于c# - Entity Framework : mapping tinyint to boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4017094/

相关文章:

spring - Tiles 2 且未找到带有 URI 的 HTTP 请求的映射 - Spring-MVC

c# - 如何通过cmd运行windows窗体应用程序

c# - ThreadAbortException 与 C# 中的优雅事件句柄退出

c# - 将委托(delegate)用法从 C# 转换为 VB

asp.net - 如何在 EntityDataSource 中使用 CASE 语句进行排序?

c# - 首先在 EF4.1 代码中,使用注释、配置文件或在 OnModelCreating 中配置实体有什么区别?

c# - Entity Framework -> 从 DB 中一条一条地获取记录或一次获取它们。哪个更快?

vim - 使用Vim命令将文本插入多行

c# - 轻松地将 XML 节点映射到对象的属性

c# - Xamarin 表单读取本地 json 文件并显示在选择器中