32

EF5 で使用する列挙型と、対応するルックアップ テーブルを定義したいと思います。EF5が列挙型をサポートするようになったことは知っていますが、すぐに使用できるように、これはオブジェクトレベルでのみサポートされているようで、デフォルトではこれらのルックアップ値のテーブルを追加しません.

たとえば、 User エンティティがあります。

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)
)

これは可能ですか?

4

6 に答える 6

18

直接はできません。EF は .NET と同じレベルで列挙型をサポートしているため、列挙型の値は単に整数という名前です => クラスの列挙型プロパティは常にデータベースの整数列です。テーブルも必要な場合は、外部キーと共に独自のデータベース初期化子で手動で作成しUser、列挙値を入力する必要があります。

より複雑なマッピングを可能にするために、ユーザーの声についていくつか提案しました。役立つと思われる場合は、提案に投票できます。

于 2012-06-23T22:36:27.173 に答える
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);
        }
    }

}
于 2013-02-25T11:01:17.203 に答える
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
}
于 2014-10-10T00:03:33.643 に答える
-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
于 2012-06-23T08:29:53.093 に答える