I have a model for my database (using efcore to translate between model and database) that contains a string that can be three values.
In order to better control the string values going into the db, I created an enum of sorts (which you can't do in C# so I followed this model).
public class MyModelClass
{
public int Id { get; protected set; }
public string MyString { get; protected set; }
public MyModelClass(int id, MyTranslatingType type)
{
Id = id;
MyString = type.Value;
}
public class MyTranslatingType
{
private MyTranslatingType(string value) { Value = value; }
public string Value { get; set; }
public static MyTranslatingType FirstType
=> new MyTranslatingType(nameof(FirstType));
public static MyTranslatingType SecondType
=> new MyTranslatingType (nameof(SecondType));
public static MyTranslatingType ThirdType
=> new MyTranslatingType (nameof(ThirdType));
}
}
However, when I try to grab values from the database, I can't just cast them, or use typeof()
because they are properties and not a traditional enum/type.
I have tried
// error saying it can't convert [PropertyInfo][2] to MyModelClass.MyTranslatingType
MyModelClass.MyTranslatingType myType = typeof(MyModelClass.MyTranslatingType).GetProperty("ThirdType");
// error saying it can't convert string to MyModelClass.MyTranslatingType
MyModelClass.MyTranslatingType myType = (MyModelClass.MyTranslatingType)"ThirdType";
How can I cast a string of "ThirdType"
to a property like MyModelClass.MyTranslatingType.ThirdType
?
In other words, I want myType
to equal MyModelClass.MyTranslatingType.ThirdType
for
var myType = (MyModelClass.MyTranslatingType)"ThirdType"