Thursday, March 31, 2011

Put logic behind generated LinqToSql fields

In a database I use throughout several projects, there is a field that should actually be a boolean but is for reasons nobody can explain to me a field duplicated over two tables where one time it is a char ('Y'/'N') and one time an int (1/0). When I generate a datacontext with LinqToSql the fields off course gets these datatypes.
It would be nice if I don't have to drag this stupid choice of datatype throughout the rest of my application. Is there a way to give the generated classes a little bit of logic that just return me

return this.equals('Y');
and
return this==1;

Preferably without having to make an EXTRA field in my partial class.
It would be a solution to give the generated field a totally different name that can only be accessed through the partial class and then generate the extra field with the original name with my custom logic in the partial class. I don't know how to alter the accesibility level in my generated class though..

Any suggestions?

From stackoverflow
  • Just create a property to translate the char value into a boolean, you can use this to get and set the char value based on your boolean input.

    This can be done in a partial class.

    borisCallens : Yes, indeed, but it was the invisible part that i was looking for :)
  • Right-clicking and selecting "Properties" of the property in the LINQ-To-Sql designer will allow you to alter the visibility. Next, you can provide an implementation with your desired logic in your partial class.

    leppie : Heh, I missed the visibilty part +1 for alertness :)
    borisCallens : By making the property use the original private property, Linq to Sql is not able to use this property in it's generated sql queries though. That's a downer :(

0 comments:

Post a Comment