ef-enum-to-lookup
ef-enum-to-lookup copied to clipboard
Support for/ignore option for Flags Enum?
EfEnumToLookup automatically generates lookup table and FK for flags enums.
However, the foreign key constraint will fail if one stores 2 or more flags in the enum property.
I.e. something like this will fail:
public class SomeConfiguration
{
[Key]
public long Id {get;set;}
public TraceOutputChannelType OutputChannels { get; set; }
}
[Flags]
public enum TraceOutputChannelType
{
Console = 1,
Disk = 2
}
[Test]
public void ShouldSaveEnumFieldWithMultipleFlags()
{
using (var context = new MagicContext())
{
var config = new SomeConfiguration
{
OutputChannels = TraceOutputChannelType.Console | TraceOutputChannelType.Disk
};
context.SomeConfigurations.Add(config);
context.SaveChanges(); //FK generated by Ef-Enum-To-lookup throws error on non-existing key '3' in table Enum_TraceOutputChannelType
}
}
I realize that lookup tables may not convey any meaning for flags enums, especially considering the flags defined can be "overlapping" (i.e. in this example, I could define a 3rd enum member "All", with the value 3).
Is there a way to configure Ef-Enum-To-Lookup to ignore the enum type/all properties using it when generating the SQL?
My workaround so far has simply been to remove the generated FK constraint after it is generated.
Thanks for raising this, it's a good point!
I wonder if
- we can detect flags enums automatically through reflection (I would expect so but haven't checked)
- if we can think of a way doing something something more useful in the database
I had a look at the code and there's currently code for ignoring a particular value but not a whole enum. I wonder if we still want the lookup table to be generated, might still be useful. Note to self: needs more research I think.
You could actually support this case as well. First of all it's easy to find if a particular Enum type has FlagAttribute set which is all that is required. If this is the case instead of adding a foreign key constraint for the column one could add a check constraint and use bit masking to check if entered value is valid for column. This would be quite easy to implement.
Does anyone have a working solution/workaround for this?
Any solutions yet for this request?
I won't be doing more coding on this unless I can figure out a source of funding. Suggestions welcome. See / comment on #58