18

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?

Nathan Koop
  • 24,803
  • 25
  • 90
  • 125
  • Why would you ever need that instead of a bool? – Jonas Stensved Feb 28 '15 at 11:24
  • @JonasStensved the problem was that the database table that I was using had the incorrect datatype in it. Once I changed the table to use a `bit` instead of a `byte` then everything worked perfectly. – Nathan Koop Mar 02 '15 at 14:18

2 Answers2

19

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

shA.t
  • 16,580
  • 5
  • 54
  • 111
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
  • 1
    Thanks, bit is certainly the correct datatype to use in this situation – Nathan Koop Sep 18 '09 at 18:19
  • And what if I'm using a View? – Bruno Machado - vargero Feb 09 '12 at 19:20
  • @Bruno Views should be used the same as tables if you are using Code First (mapping from the DB to the Model) if you are using an EDMX try [this article](http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/) – onetwopunch Jun 28 '12 at 23:07
  • Spent a long time trying to address this until I found this post. DB first MySQL Linq EF6. I changed all tinyint(1) NOT NULL DEFAULT FALSE to BIT(1) NOT NULL DEFAULT b'0' and for the moment life is blissful. This was the error I was previously seeing "String was not recognized as a valid Boolean." – sobelito Jul 11 '16 at 12:23
3

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; }
    }
}
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132