timabell / ef-enum-to-lookup

Generates lookup tables from enum references in Microsoft Entity Framework 6.1
https://www.nuget.org/packages/ef-enum-to-lookup
69 stars 29 forks source link

Support for/ignore option for Flags Enum? #55

Open andreasnilsen opened 7 years ago

andreasnilsen commented 7 years ago

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.

timabell commented 7 years ago

Thanks for raising this, it's a good point!

I wonder if

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.

kavhad commented 6 years ago

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.

GFoley83 commented 6 years ago

Does anyone have a working solution/workaround for this?

lostintranslation commented 5 years ago

Any solutions yet for this request?

timabell commented 5 years ago

I won't be doing more coding on this unless I can figure out a source of funding. Suggestions welcome. See / comment on #58