Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is easiest way to deal with converting 0/1 to False/True in EF 4.x?

The stored Proc returns a column with the value to be either 0 or 1 without converting to BIT. In my POCO, if I declare the field as

public bool MyColumn {get; set;}

I am getting this error:

The specified cast from a materialized 'System.Int32' type to the 'System.Boolean' type is not valid.

This actually makes sense since EF recognizes the returned value as an integer.

I am wondering that is there any easy way to (add annotation or use fluent api maybe) automatically convert 0/1 to False/True in the mapping behind the scene without touching the Proc?

Thanks in advance!

like image 702
zs2020 Avatar asked Aug 02 '12 18:08

zs2020


People also ask

How do you convert 1 and 0 to true and false?

Multiply original formula by 1 Note: You can also divide original formula by 1 or add 0 to original formula to change the return TRUE to 1 and FALSE to 0.

What are value converters in EF?

Value converters allow property values to be converted when reading from or writing to the database.

Is 0 false in c#?

The C# example must be compiled with the /unsafe switch. The byte's low-order bit is used to represent its value. A value of 1 represents true ; a value of 0 represents false .

What is OnModelCreating in Entity Framework?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.


1 Answers

In your ApplicationDbContext (the class that inherits from DbContext) you can use Fluent Api to convert values for the database.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);
  modelBuilder.Entity<TheNameOfYourModelClass>()
    .Property(p => p.MyColumn)
    .HasConversion(
       v => v ? 1 : 0,
       v => (v == 1));
}

Now, your database will contain 1 when inserting a true for MyColumn and vice-versa. When reading from your database 1 will be converted to true and vice-versa.

like image 142
Jimmy Avatar answered Oct 08 '22 07:10

Jimmy