Ivan
Ivan

Reputation: 64207

How to map an Int database field to a Boolean Entity Framework model field?

An Int field is used (for compatibility with other DBMSes and programming languages) to store a Boolean value in the database. How am I to customize the database-first generated Entity Framework model (which maps an Int field to Int32 by default) to make sure it will use 1/0 (instead of "true"/"false") in SQL queries generated while using Boolean type on the application side?

Upvotes: 3

Views: 1924

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

One work around is to use another Boolean property in the model which is not mapped to the DB. And in that property set method you can set the integer value to the int property.

//EF Generated/Poco Do not Modify
public partial MyTable
{
  public int MyField { get; set; }
}

Since these are partial classes create another file

public partial MyTable
{
  public bool MyBoolField
  {
    get
    {
      return this.MyField != 0;
    }
    set
    {
      if (value)
      {
        this.MyField = 1;
      }
      else 
      {
        this.MyField = 0;
      }

    }
  }
}

Upvotes: 3

Related Questions