将CodeFirst的属性保存到EFCore中的Base64字符串,但是从EFCore读回X509Certificate2?

时间:2017-10-23 15:29:55

标签: entity-framework ef-core-2.0

ThirdParty模型包含属性Certificate。它是源代码使用的X509Certificate2数据类型,但EFCore不支持它,这意味着我必须将其转换为Base64 string以进行EFCore数据库存储。然后在从EFCore数据库读取时将其转换回X509Certificate2

我们如何指示EFCore使用任何属性映射器自动执行此操作?

public class ThirdParty
{
   public Guid ThirdPartyId { get; set; }
   public X509Certificate2 Certificate { get; set; }
   public string RawData { get; set; }
   public DateTime CreatedDate { get; set; }
}

var certificate1 = new X509Certificate();
var thirdParty = new ThirdParty() { Certificate = certificate }
var certificate2 = thirdParty.Certificate;

2 个答案:

答案 0 :(得分:1)

一种方法是添加一个其他未映射的属性,它将返回将从X509Certificate2 Base64创建的string对象。从数据库中读取。 因此,CertificateString属性仅用于保存和读取数据上下文,Certificate属性用于其他逻辑。

public class ThirdParty
{
    private X509Certificate2 _certificate;



    public Guid ThirdPartyId { get; set; }

    // to write in data context only - only set it in production code
    public string CertificateString 
    {
        get
        {
            // return the Base64 string - is just pseudo code
            return _certificate?.ToString();
        }    
        set
        {
            _certificate = new X509Certificate2(value);
        }
    }

    // not mapped for data context - to read from data context only - only read fro
    public X509Certificate2 Certificate
    {
        get
        {
            if (string.IsNullOrWhiteSpace(CertificateString))
            {
                return default(X509Certificate2);
            }

            return new X509Certificate2(CertificateString);
        }    
        private set
        {
            // will be set by CertificateString
        }
    }

    public string RawData { get; set; }

    public DateTime CreatedDate { get; set; }
}

要不映射属性,您可以使用[NotMapped]作为数据注释或使用Fluent API中的.Ignore(p => p.PropertyName)

答案 1 :(得分:0)

我会做这样的事情,如果您在序列化证书方面遇到问题,可以看看Why does Json.NET fail to serialize a X509Certificate2?

public class Configuration : IEntityTypeConfiguration<ThirdParty>
{
    public void Configure(EntityTypeBuilder<ThirdParty> builder)
    {
        // This Converter will perform the conversion to and from Json to the desired type
        builder.Property(e => e.Certificate).HasConversion(
            v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
            v => JsonConvert.DeserializeObject<X509Certificate2>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
    }
}