c# - Store bool Property as integer with Npgsql and Entity Framework -


i'am using entity framework 6.1 npgsql 2.2.5 driver.

entity

public class myentity {     public bool deprecated { get; set; } } 

mapping

public class myentitymap : entitytypeconfiguration<myentity> {     public myentitymap ()     {         property(t => t.deprecated)             .hascolumnname("status")             .hascolumntype("integer")             .isoptional();     } } 

when try read database, exception, not directly related mapping:

invalidoperationexception "sequence doesn't contain matching element" (translated german, don't know exact english text)

is possible store boolean property integer? did workaround introducing new property status of type int, mapped status column. added notmappedattribute deprecated, made return status != 0 int getter , setting status 1 or 0. working, can't use deprecated in linq queries.

i'd change datatype of column, there legacy system using database well. introducing new column , keep both in sync database triggers solution, model has of these issues. i'd have more generic solution.

is there better way?

yeah... same problem here.

i don't think there's clean way unless modify source npgsql ef provider.

public static class dbvalue {     public const int false = 0; //or } public class myentity {      [column("deprecated")]     public integer deprecatedstatus { get; set; }     [notmapped]     public bool deprecatedbool      {          { this.deprecatedstatus != 0 }         set { this.deprecatedstatus = (value ? 1 : 0) }     } }  //then in linq db.myentities.where(e => e.deprecatedstatus == dbvalue.false);  //and db.myentities.where(e => e.deprecatedstatus != dbvalue.false); 

oh, hey thought of idea. write expression objects in code , pass them linq (since iqueryable<> uses expressions)

so this:

public class myentity {     public static expression<func<myentity, bool>> isdeprecated = (myentity) => myentity.deprecated != 0;     public static expression<func<myentity, bool>> isnotdeprecated = (myentity) => myentity.deprecated == 0;     public integer deprecated{ get; set; }  } //then in linq db.myentities.where(myentity.isdeprecated);  //and db.myentities.where(myentity.isnotdeprecated); 

the reason using expressions instead of func stuff can little confusing novices, pattern easy follow if you're comfortable lambda expressions. i've done kind of thing before , works. doesn't work trying dynamically create expression objects at runtime because goes awry in ef code. (only compiler geeks think anyway)

so disadvantage here every time have expression in linq want use deprecated property, have create static expression object.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -