Skip to content

Commit

Permalink
Merge pull request #5 from cioxideru/master
Browse files Browse the repository at this point in the history
try to fix problem with many fields with same enum type
  • Loading branch information
pergerch authored Nov 27, 2018
2 parents 4dec17a + 6c500f8 commit 934af2a
Showing 1 changed file with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
namespace SpatialFocus.EntityFrameworkCore.Extensions
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
Expand All @@ -14,6 +15,8 @@ namespace SpatialFocus.EntityFrameworkCore.Extensions

public static class EnumLookupExtension
{
private static List<Type> ConcreteTypeSeededList { get; set; } = new List<Type>();

// See https://github.com/aspnet/EntityFrameworkCore/issues/12248#issuecomment-395450990
public static void ConfigureEnumLookup(this ModelBuilder modelBuilder, EnumLookupOptions enumOptions)
{
Expand All @@ -26,7 +29,7 @@ public static void ConfigureEnumLookup(this ModelBuilder modelBuilder, EnumLooku
continue;
}

if (enumOptions.UseEnumsWithAttributesOnly && !propertyType.GetCustomAttributes(typeof(EnumLookupAttribute), true).Any())
if (enumOptions.UseEnumsWithAttributesOnly && !propertyType.HasEnumWithAttribute())
{
continue;
}
Expand Down Expand Up @@ -61,6 +64,13 @@ public static void ConfigureEnumLookup(this ModelBuilder modelBuilder, EnumLooku
modelBuilder.Entity(concreteType).Property(keyName).HasConversion(valueConverter);
}

if (ConcreteTypeSeededList.Contains(concreteType))
{
continue;
}

ConcreteTypeSeededList.Add(concreteType);

// TODO: Check status of https://github.com/aspnet/EntityFrameworkCore/issues/12194 before using migrations
object[] data = Enum.GetValues(propertyType.GetEnumOrNullableEnumType())
.OfType<object>()
Expand Down Expand Up @@ -96,6 +106,24 @@ private static Type GetEnumOrNullableEnumType(this Type propertyType)
return propertyType.IsEnum ? propertyType : propertyType.GetGenericArguments()[0];
}

private static bool HasEnumWithAttribute(this Type propertyType)
{
if (propertyType.GetCustomAttributes(typeof(EnumLookupAttribute), true).Any())
{
return true;
}

if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (propertyType.GetGenericArguments()[0].GetCustomAttributes(typeof(EnumLookupAttribute), true).Any())
{
return true;
}
}

return false;
}

private static bool IsEnumOrNullableEnumType(this Type propertyType)
{
if (propertyType.IsEnum)
Expand Down

0 comments on commit 934af2a

Please sign in to comment.