Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set model property to boolean in Entity Framework

I am just starting to learn a bit about the entity framework and don't have much experience with ORM's.

In my little app I have one table, this sql server table has several columns including a PrimaryKey (int) a Name (string) and a Flag (tinyint).

When I imported this table into it automatically assigned the Flags' datatype as a byte. This is fine, but the Flag should really be a boolean, so I

  1. Clicked on the Mapping Details
  2. Selected my Flag property
  3. Changed the Type from Byte to Boolean
  4. Rebuilt the application

I then got this error:

Error 2019: Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=True,DefaultValue=]' of member 'MyFlag' in type 'MyModel.MyItem' is not compatible with 'SqlServer.tinyint[Nullable=True,DefaultValue=]' of member 'MyFlag' in type 'MyModel.Store.MyItem'.

Is there a way to have

MyItem item = new MyItem();
item.Flag = true;

and have Flag save to 1 in the database?

like image 489
Nathan Koop Avatar asked Sep 18 '09 18:09

Nathan Koop


2 Answers

You could change the datatype of MyFlag to bit in the database.

like image 186
Shiraz Bhaiji Avatar answered Oct 11 '22 03:10

Shiraz Bhaiji


I think for the tinyint you will have to make a partial class and use a separate field that appropriately read/writes to that field. However the framework will correctly interpret bit fields as boolean.

You could try something like below as the partial..

public partial class MyItem
{
    public bool FlagBool
    {
        get { return Flag == 1; }
        set { Flag = value ? 1 : 0; }
    }
}
like image 3
Quintin Robinson Avatar answered Oct 11 '22 03:10

Quintin Robinson