如何让MySql和EF Core将tinyint或bit映射到布尔值?

huangapple go评论93阅读模式
英文:

How to make MySql and EF Core to map tinyint or bit to boolean?

问题

我有一个.NET Core项目,在其中我使用EF Core来生成我们的MySql数据库(采用数据库优先的方法)。我无法使EF Core将tinyint或bit映射为bool。它将tinyint映射为byte,将bit映射为short。有人有什么想法吗?

英文:

I have a .NET Core project where I use EF Core to scaffold our MySql database (db first approach). I'm not able to make EF Core to map tinyint or bit as bool. It maps tinyint to byte and bit to short. Does anyone have any ideas?

答案1

得分: 3

你可以为 Entity Framework 生成的部分类编写元类。

假设你有一个名为 Status 的类,如下所示:

public class Status {
    public int Value { get; set; }
}

你可以像下面这样为它编写元类:

[ModelMetadataType(typeof(TblUserMetaData))]
public partial class Status {
}

public class TblUserMetaData {
    public int Value { get; set; }
    public bool ValueBool {
        get {
            // 通过转换布尔值获取 Value 变量
        }
        set {
            // 通过转换整数设置 Value 变量
        }
    }
}
  • 你需要将元类放在相同的命名空间中。
英文:

You can write meta classes for generated partial classes from entity framework.

lets assume you have a class call Status like bellow

public class Status{
public int Value{get;set;}
}

you can write meta class for it like bellow.

 [ModelMetadataType(typeof(TblUserMetaData))]
        public partial class Status
        {
        }
    
        public class TblUserMetaData
        {
           public int Value{get;set;}
           public bool ValueBool{get{ 
            //gett Value variable by converting boolean
            };
         set{
             //set Value variable by converting int
           };
          }
        }
    }
  • you need to place meta class in same namespace

答案2

得分: 2

请确保您正在使用Pomelo.EntityFrameworkCore.MySql作为您的MySQL EF Core提供程序。(它已经支持EF Core 3.0,并且比Oracle的包更可靠。)

自3.0版本起,将TINYINT(1)映射为System.Boolean是默认设置(参考链接),只要您的连接字符串包括TreatTinyAsBoolean=True(如果未明确设置,这是默认设置)。

英文:

Make sure you're using Pomelo.EntityFrameworkCore.MySql as your MySQL EF Core provider. (It already supports EF Core 3.0 and is more reliable than Oracle's package.)

Since 3.0, mapping TINYINT(1) to System.Boolean is the default (reference), as long as your connection string includes TreatTinyAsBoolean=True (which is the default setting if not explicitly set).

huangapple
  • 本文由 发表于 2020年1月3日 19:05:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定