【问题标题】:Entity framework fluent api how to map dynamically from class attribute实体框架流利的api如何从类属性动态映射
【发布时间】:2021-03-25 11:34:55
【问题描述】:

我想将 jsonproperty 属性映射到实体列名而不显式映射每个列名 (Azure Cosmos DB (EF/Core) - Camel Case Property Names)

这是模型

public class FooModel
{
    public Guid Key { get; set; }

    public Bar Value { get; set; }
}


public class Bar
{
    [JsonProperty(PropertyName = "property_1")]
    public string Property1 { get; set; }

    [JsonProperty(PropertyName = "property_2")]
    public string Property2 { get; set; }
}
    

实体使用 Fluent API 进行配置。

modelBuilder.Entity<Entity<Asn>>(entity =>
{
    entity.HasKey(e => e.Key)
        .HasName("key");

    entity.ToTable("foo", "dbo");

    entity.Property(e => e.Key)
        .HasColumnName("key")
        .ValueGeneratedNever();

    entity.Property(e => e.Value)
        .IsRequired()
        .HasColumnName("value")
        .HasColumnType("jsonb");
});

我可以从类型中读取所有属性并读取自定义属性,但是如何使用entity.Property() 进行映射?

type.GetProperties()
    .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>())
    .Select(jp => jp.PropertyName)

【问题讨论】:

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


    【解决方案1】:

    您不会迭代 CLR 类型的属性。而是迭代模型的实体属性,这些属性引用了 CLR PropertyInfo,但也是配置列名映射的正确位置。

    例如

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    
        var q = from et in modelBuilder.Model.GetEntityTypes()
                from p in et.GetProperties()
                where !p.IsShadowProperty()
                where p.PropertyInfo.GetCustomAttribute<JsonPropertyAttribute>() != null
                select p;
    
        foreach (var p in q)
        {
            var columnName = p.PropertyInfo.GetCustomAttribute<JsonPropertyAttribute>().PropertyName;
            if (columnName != null)
            {
                p.SetColumnName(columnName);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      相关资源
      最近更新 更多