Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do property type conversion in EF 4.1 Code First

I want to create EF 4.1 Code first models from an existing SQL database schema and I am wondering if it is possible to do some type conversion of property data.

For example, I have an existing table "Foo" having a field like this:

isTrue char(1) 'valid values are "Y" or "N"

In my EF 4.1 Code First model, I want to convert this field into a boolean type like:

public class Foo
{
    public bool isTrue { get; set; }  
}

Is this possible in EF 4.1 Code First by extending DBContext or adding extra code in the model or EntityTypeConfiguration<> sub-class? If yes, can somebody point me to a link or some documentation on how to do it? Refactoring the database fields is not possible at this time.

like image 564
topnotch228 Avatar asked Jun 14 '11 15:06

topnotch228


3 Answers

It is possible to use a non-mapped field that is public which uses an internal field and then you can save and retrieve with code first and do the mapping here. This would needs to be done for each field that need to be converted or, of course, simplied with a helper method

internal string YesNo { get; set; }

private bool _bYesNo;
[NotMapped]
public bool bYesNo
{
  get{return (YesNo == "Y") ? true : false;}
  set{_bYesNo = value;YesNo = (bYesNo) ? "Y" : "N";}
}
like image 101
greenmountains253 Avatar answered Jan 03 '23 11:01

greenmountains253


It's not possible to have EF do the conversion.

One possible workaround is making EF ignore the bool property, and using a wrapper property that converts true to "Y" and false to "N".


If you usually need this kind of flexibility, I suggest you look into more mature frameworks.

NHibernate, for example, supports this requirement out of the box, by specifying YesNo as the mapping type.

like image 32
Diego Mijelshon Avatar answered Jan 03 '23 11:01

Diego Mijelshon


I had the same problem and the following solution worked out great for me!!

Entity Framework and Oracle Boolean

In my code a table field just looks like a normal boolean, but in the database it is a char(1): The EF model will convert it into "Y" or "N" and saves it to the database. I also do the same trick for Guid into char(36).

like image 21
Romald Avatar answered Jan 03 '23 12:01

Romald