Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

c# - Entity Framework: mapping tinyint to boolean

by default Entity Framework maps tinyint to byte.

i tried changing the underlying type after it was generated to Boolean, but getting compilation error

Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=False,DefaultValue=]' of member blah...

is this possible in 4.0?

it wasn't my idea to use tinyint column as boolean. this was done automatically by another team using hibernate which apparently does it that way for mysql compatibility. obviously tinyint has more values than 2. I am looking for a way to map it so that anyting accept for 1 is false, or anything accept for 0 is true. either would work for me

is there a way to plug in a type translator of sorts into EF?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your existing database has a tinyint column that you wish to represent as a Boolean property of your C# class, then you can do this as follows:

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

Obviously this assumes that 0 and 1 correspond to false and true, respectively. In this sample, the autoRenew is nullable and null is interpreted as false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...