Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...