使用EF Core枚举属性进行映射

时间:2019-09-16 21:06:13

标签: c# .net entity-framework entity-framework-core

我有一个Person类,其属性为CardType

choice = false
Alert.alert(
    "Delete?", 
    "", [ 
        { text: 'Cancel, onPress: () => { choice = 'cancel' }, style: 'cancel' },
        { text: 'OK',    onPress: () => { choice = 'ok' } } 
    ], 
    { onDismiss: () => { choice = 'cancel' }} 
)

await until(() => choice)

if (choice === 'ok') {
    ...
}

我正在尝试使用EF Core映射CardType属性

public class Person{
    protected Person(){}    
    public Person(CardType cardType){
       cardType = CardType;
    }

    public CardType CardType { get; private set; }
    ... other properties ommited
}



public class CardType : Enumeration
{
    public static CardType Amex = new CardType(1, "Amex");
    public static CardType Visa = new CardType(2, "Visa");
    public static CardType MasterCard = new CardType(3, "MasterCard");

    public CardType(int id, string name)
        : base(id, name)
    {
    }
}

但是我正在关注:

  

属性“ Person.CardType”的类型为“ CardType”,但不是   当前数据库提供者支持。更改属性CLR   使用[[NotMapped]]属性或通过键入或忽略属性   在'OnModelCreating'中使用'EntityTypeBuilder.Ignore'。

2 个答案:

答案 0 :(得分:0)

您不能将自定义类用作数据属性的类型(它们只能在导航属性中使用)。您需要使用枚举:

public enum CardType
{
    Default = 0,
    Amex,
    Visa,
    MasterCard
}

答案 1 :(得分:0)

仅在db中存储一个Enumeration对象的ID,还可以利用HasConversion方法来来回地转换枚举类型

builder.Property(c => c.CardType).HasConversion(c => c.Id, c => CardType.From(c));

“发件人”方法可以从提供的ID实例化枚举

相关问题