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.
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";}
}
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With