1

Working with an application which uses a home-grown entity framework which comes as a referenced DLL (no source code), I have to access SQL data using its methods, like:

var allMyClasses = EF.ReadTable<MyClass>("select a, b, c from myTable")

This call returns IList<MyClass>. Whenever MyClass has a string member, which can take a value from a pre-defined list, I am tempted to refactor it into an enum as follows:

enum Things{ Something, Anotherthing }

class MyClass{
  public int a {get; set;}
  public Things b {get; set;}

  public void set_b(string value)
  {
    if(Enum.TryParse(value, out Things th))
    {
      b = th;
    }
    else throw new ArgumentException("Unsupported thing: {}", th);
  }

  public string c {get; set;}
}

My assumption was that as long as there was an overloaded setter for b which took a string argument, conversion from the string retrieved from the DB to the enum Things should be automatic. Instead I keep getting a runtime exception:

System.ArgumentException: 'Object of type 'System.String' cannot be converted to type 'Things'.'

This is a shortcoming of the homegrown EF which does not know how to assign a string to an enum. Is there any way to work around that in my code without writing more than a few lines of code?

ajeh
  • 2,652
  • 2
  • 34
  • 65
  • *which uses a home-grown entity framework which comes as a referenced DLL* it sounds.. dangerous.. regarding the `enum` things, perhaps you could use static classes to store the string options.. since [c#'s enum can't store string](https://stackoverflow.com/questions/630803/associating-enums-with-strings-in-c-sharp).. which kind of sad.. – Bagus Tesa Feb 28 '18 at 23:31
  • You can't overload setters in C# like that, can you? Or is this a C#7 thing? Even without the custom EF, you'd get a compile error about "Cannot implicitly convert `string` to `Things`" if you tried to do `var foo = new MyClass { b = "Something" };` – Rufus L Mar 01 '18 at 00:09
  • Maybe if you put the code in your setter instead of in a totally different function it may work... – Gusman Mar 01 '18 at 00:41
  • But why do you think "set_b" method has any relation to `b` property? It's completely separate one and has nothing to do with `b`. – Evk Mar 01 '18 at 04:43
  • @Gusman Did you try to create a setter which would take a `string` value parameter for an `enum` field? And did that work? – ajeh Mar 01 '18 at 16:00
  • @ajeh Obviously it doesn't works just pasting your code in the setter, but a sepparate function which is never called will do nothing. The solution is to change the type of `b` from `Thing` to `string` or `object` and create another property called `bThing` of type `Thing` and set the value of `bThing` from the `b` setter. – Gusman Mar 01 '18 at 18:16
  • @Gusman I'd rather not hack it that way as it would make code less readable than it is now, before my attempted change. – ajeh Mar 01 '18 at 20:09

0 Answers0