web-dev-qa-db-ja.com

EntityFrameworkの文字列列を列挙型にマップします

文字列列をエンティティモデルの列挙型にマップする方法はありますか?

私はこれをHibernateで実行しましたが、EMFでは理解できません。

21

醜いですが、列挙型を文字列にマッピングするために、次のようなものを見つけました。

public virtual string StatusString
{
    get { return Status.ToString(); }
    set { OrderStatus newValue; 
          if (Enum.TryParse(value, out newValue))
          { Status = newValue; }
        }
}

public virtual OrderStatus Status { get; set; } 

OrderStatusは列挙子タイプ、Statusは列挙子、StatusStringはその文字列バージョンです。

13
kroonwijk

おそらくより良いバージョンです。

OrderStateIdentifierフィールドはJSONシリアル化とデータベースフィールドの両方に使用されますが、OrderStateは便宜上コードでのみ使用されます。

    public string OrderStateIdentifier
    {
        get { return OrderState.ToString(); }
        set { OrderState = value.ToEnum<OrderState>(); }
    }

    [NotMapped]
    [JsonIgnore]
    public OrderState OrderState { get; set; }


public static class EnumHelper
{
    /// <summary>
    /// Converts string to enum value (opposite to Enum.ToString()).
    /// </summary>
    /// <typeparam name="T">Type of the enum to convert the string into.</typeparam>
    /// <param name="s">string to convert to enum value.</param>
    public static T ToEnum<T>(this string s) where T: struct
    {
        T newValue;
        return Enum.TryParse(s, out newValue) ? newValue : default(T);
    }
}
21
Crulex

次のいずれかを実行できます。

クラスのEnumプロパティをテキスト列として装飾します

[Column(TypeName = "nvarchar(50)")]
public FileTypes FileType { get; set; }

OR

DatabaseContextクラスで、OnModelCreatingをオーバーライドし、以下を追加します。

modelBuilder
  .Entity<File>()
  .Property(e => e.FileType)
  .HasConversion(new EnumToStringConverter<FileTypes>());
6
nivs1978

別の方法は、列挙型の代わりに文字列constフィールドを持つ静的クラスを使用することです。

例えば:

public class PocoEntity
{
    public string Status { get; set; }
}

public static class PocoEntityStatus
{
    public const string Ok = "ok";
    public const string Failed = "failed";
}

データベース側で検証を追加するために、チェック制約を追加して、列が期待値であることを確認できます(列挙型にマッピングするときにもこれを行うことができますが、プロパティは単なる文字列であるため、これにより、 apiは値を適切に設定します)。

ALTER TABLE [PocoEntity]
    ADD CONSTRAINT [CHK_PocoEntity_Status]
    CHECK ([Status] in ('ok', 'failed'));
2
jt000

実際、これには別の解決策があると思います。

私たちのプロジェクトで最近行ったことは、拡張メソッドを使用することでした。

列挙型用とエンティティ用の2つを作成しましたが、例を次に示します。

namespace Foo.Enums
{
    [DataContract]
    public enum EAccountStatus
    { 
        [DataMember]
        Online,
        [DataMember]
        Offline,
        [DataMember]
        Pending
    }

...列挙型自体、そして静的クラスを含む拡張メソッド:

    public static class AccountStatusExtensionMethods
    {

        /// <summary>
        /// Returns the Type as enumeration for the db entity
        /// </summary>
        /// <param name="entity">Entity for which to check the type</param>
        /// <returns>enum that represents the type</returns>
        public static EAccountStatus GetAccountStatus(this Account entity)
        {
            if (entity.AccountStatus.Equals(EAccountStatus.Offline))
            {
                return EAccountStatus.Offline;
            }
            else if (entity.AccountStatus.Equals(EAccountStatus.Online))
            {
                return EAccountStatus.Online;
            }
            else if (entity.AccountStatus.Equals(EAccountStatus.Pending))
            {
                return EAccountStatus.Pending;
            }
            throw new System.Data.Entity.Validation.DbEntityValidationException(
                "Unrecognized AccountStatus was set, this is FATAL!");
        }

...エンティティタイプの拡張メソッド、および短い入力のための便利なメソッド:

        /// <summary>
        /// Gets the String representation for this enums choosen 
        /// </summary>
        /// <param name="e">Instance of the enum chosen</param>
        /// <returns>Name of the chosen enum in String representation</returns>
        public static String GetName(this EAccountStatus e)
        {
            return Enum.GetName(typeof(EAccountStatus), e);
        }
    }
}

...そして最後に使用法:

// to set always the same, mappable strings:
db.AccountSet.Single(m => m.Id == 1).Status = EAccountStatus.Online.GetName();

// to get the enum from the actual Entity you see:
EAccountStatus actualStatus = db.AccountSet.Single(m => m.Id == 1).GetAccountStatus();

これで、「Foo.Enumsを使用する」必要があります。エンティティと列挙型のメソッドを呼び出すことができます。さらに良いことに、エンティティのある種のラッパーでは、大きなプロジェクトで同じことを表す異なるタイプ間でシームレスなマーシャリングを行うこともできます。

これについて注意する価値がある唯一のことは、Linq式をLinqに渡す前に拡張メソッドを実行しなければならない場合があるということです。ここでの問題は、Linqが独自のコンテキストで拡張メソッドを実行できないことです...

たぶん単なる代替手段かもしれませんが、エンティティのために物事を取得する方法に大きな柔軟性を与えるので、私たちはそのようにそれを行いました。あなたは簡単にShoppingCartでアカウントの実際の製品を受け取るための拡張機能を書くことができます...

あいさつ、ケルスキー

2
Kjellski
1

列挙値を別の対応する文字列(省略形など)にマップする場合は、次の方法を使用できます。

public class MinhaClasse
{
    public string CodTipoCampo { get; set; }

    [NotMapped]
    public TipoDado TipoCampo
    {
        get => DictValorTipoDado.SingleOrDefault(e => e.Value == CodTipoCampo).Key;
        set => CodTipoCampo = DictValorTipoDado[value];
    }

    private Dictionary<TipoDado, string> DictValorTipoDado = new Dictionary<TipoDado, string>()
    {
        { TipoDado.Texto, "T" },
        { TipoDado.Numerico, "N" },
        { TipoDado.Data, "D" }
    };

    public enum TipoDado { Texto, Numero, Data }
}
1
Junior

私も同じ問題を抱えていました。私は解決策を考え出しましたが、完全には満足していません。

私のPersonクラスにはGender列挙型があり、データ注釈を使用して文字列をデータベースにマップし、列挙型を無視します。

public class Person
{
    public int PersonID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [Column("Gender")]
    public string GenderString
    {
        get { return Gender.ToString(); }
        private set { Gender = EnumExtensions.ParseEnum<Gender>(value); }
    }

    [NotMapped]
    public Gender Gender { get; set; }
}

これは、文字列から正しい列挙型を取得するための拡張メソッドです。

public class EnumExtensions
{
    public static T ParseEnum<T>(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
}

私はこれについてブログ投稿を書きました--- http://nodogmablog.bryanhogan.net/2014/11/saving-enums-as-strings-with-entity-framework/

0
Bryan