EF5 Code First Enums和Lookup Tables

时间:2012-06-23 07:14:30

标签: entity-framework ef-code-first entity-framework-5

我想定义一个要使用的EF5的枚举,以及一​​个相应的查找表。我知道EF5现在支持枚举,但开箱即用,它似乎只在对象级别支持此功能,并且默认情况下不会为这些查找值添加表格。

例如,我有一个用户实体:

public class User
{
    int Id { get; set; }
    string Name { get; set; }
    UserType UserType { get; set; }
}

UserType枚举:

public enum UserType
{
    Member = 1,
    Moderator = 2,
    Administrator = 3
}

我希望数据库生成能够创建一个表,例如:

create table UserType
(
    Id int,
    Name nvarchar(max)
)

这可能吗?

6 个答案:

答案 0 :(得分:21)

这是我之前制作的nuget包,它生成查找表并应用外键,并使查找表行与枚举保持同步:

https://www.nuget.org/packages/ef-enum-to-lookup

将其添加到项目中并调用Apply方法。

github上的文档:https://github.com/timabell/ef-enum-to-lookup

答案 1 :(得分:17)

这不是直接可能的。 EF支持与.NET相同级别的枚举,因此枚举值仅命名为integer =>类中的枚举属性始终是数据库中的整数列。如果你想拥有表,你需要在你自己的数据库初始化程序中手动创建它和User中的外键,并用枚举值填充它。

我做了一些proposal on user voice以允许更复杂的映射。如果您发现它有用,您可以投票赞成该提案。

答案 2 :(得分:9)

我编写了一个小助手类,它为UserEntities类中指定的枚举创建了一个数据库表。它还在引用枚举的表上创建外键。

所以这是:

public class EntityHelper
{

    public static void Seed(DbContext context)
    {
        var contextProperties = context.GetType().GetProperties();

        List<PropertyInfo> enumSets =  contextProperties.Where(p  =>IsSubclassOfRawGeneric(typeof(EnumSet<>),p.PropertyType)).ToList();

        foreach (var enumType in enumSets)
        {
            var referencingTpyes = GetReferencingTypes(enumType, contextProperties);
            CreateEnumTable(enumType, referencingTpyes, context);
        }
    }

    private static void CreateEnumTable(PropertyInfo enumProperty, List<PropertyInfo> referencingTypes, DbContext context)
    {
        var enumType = enumProperty.PropertyType.GetGenericArguments()[0];

        //create table
        var command = string.Format(
            "CREATE TABLE {0} ([Id] [int] NOT NULL,[Value] [varchar](50) NOT NULL,CONSTRAINT pk_{0}_Id PRIMARY KEY (Id));", enumType.Name);
        context.Database.ExecuteSqlCommand(command);

        //insert value
        foreach (var enumvalue in Enum.GetValues(enumType))
        {
            command = string.Format("INSERT INTO {0} VALUES({1},'{2}');", enumType.Name, (int)enumvalue,
                                    enumvalue);
            context.Database.ExecuteSqlCommand(command);
        }

        //foreign keys
        foreach (var referencingType in referencingTypes)
        {
            var tableType = referencingType.PropertyType.GetGenericArguments()[0];
            foreach (var propertyInfo in tableType.GetProperties())
            {
                if (propertyInfo.PropertyType == enumType)
                {
                    var command2 = string.Format("ALTER TABLE {0} WITH CHECK ADD  CONSTRAINT [FK_{0}_{1}] FOREIGN KEY({2}) REFERENCES {1}([Id])",
                        tableType.Name, enumProperty.Name, propertyInfo.Name
                        );
                    context.Database.ExecuteSqlCommand(command2);
                }
            }
        }
    }

    private static List<PropertyInfo> GetReferencingTypes(PropertyInfo enumProperty, IEnumerable<PropertyInfo> contextProperties)
    {
        var result = new List<PropertyInfo>();
        var enumType = enumProperty.PropertyType.GetGenericArguments()[0];
        foreach (var contextProperty in contextProperties)
        {

            if (IsSubclassOfRawGeneric(typeof(DbSet<>), contextProperty.PropertyType))
            {
                var tableType = contextProperty.PropertyType.GetGenericArguments()[0];

                foreach (var propertyInfo in tableType.GetProperties())
                {
                    if (propertyInfo.PropertyType == enumType)
                        result.Add(contextProperty);
                }
            }
        }

        return result;
    }

    private static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
    {
        while (toCheck != null && toCheck != typeof(object))
        {
            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (generic == cur)
            {
                return true;
            }
            toCheck = toCheck.BaseType;
        }
        return false;
    }

    public class EnumSet<T>
    {
    }
}

使用代码:

public partial class UserEntities : DbContext{
    public DbSet<User> User { get; set; }
    public EntityHelper.EnumSet<UserType> UserType { get; set; }

    public static void CreateDatabase(){
        using (var db = new UserEntities()){
            db.Database.CreateIfNotExists();
            db.Database.Initialize(true);
            EntityHelper.Seed(db);
        }
    }

}

答案 3 :(得分:1)

我为它创建了一个包

https://www.nuget.org/packages/SSW.Data.EF.Enums/1.0.0

使用

EnumTableGenerator.Run("your object context", "assembly that contains enums");

&#34;你的对象上下文&#34; - 是你的EntityFramework DbContext &#34;包含枚举的程序集&#34; - 包含您的枚举的程序集

调用EnumTableGenerator.Run作为种子功能的一部分。这将在sql server中为每个Enum创建表,并使用正确的数据填充它。

答案 4 :(得分:1)

我已经包含了这个答案,因为我已经从@HerrKater

做了一些额外的更改

我对Herr Kater's Answer做了一点补充(也基于Tim Abell的评论)。更新是使用一种方法从DisplayName属性获取枚举值,如果存在,则拆分PascalCase枚举值。

 private static string GetDisplayValue(object value)
 {
   var fieldInfo = value.GetType().GetField(value.ToString());

   var descriptionAttributes = fieldInfo.GetCustomAttributes(
     typeof(DisplayAttribute), false) as DisplayAttribute[];

   if (descriptionAttributes == null) return string.Empty;
   return (descriptionAttributes.Length > 0)
   ? descriptionAttributes[0].Name
   : System.Text.RegularExpressions.Regex.Replace(value.ToString(), "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
 }

更新Herr Katers示例调用方法:

 command = string.Format("INSERT INTO {0} VALUES({1},'{2}');", enumType.Name, (int)enumvalue,
                                        GetDisplayValue(enumvalue));

枚举示例

public enum PaymentMethod
{
    [Display(Name = "Credit Card")]
    CreditCard = 1,

    [Display(Name = "Direct Debit")]
    DirectDebit = 2
}

答案 5 :(得分:-3)

您必须自定义生成工作流程

1. Copy your default template of generation TablePerTypeStrategy

Location : \Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen.

2. Add custom activity who realize your need (Workflow Foundation)

3. Modify your section Database Generation Workflow in your project EF
相关问题