简体   繁体   中英

Entity framework fluent api how to map dynamically from class attribute

I want to map jsonproperty attributes to entity column name without explicitly mapping each column name ( Azure Cosmos DB (EF/Core) - Camel Case Property Names )

This is the model

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; }
}
    

The entity is configured with the 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");
});

I can read all properties from the type and read custom attribute but how to map with entity.Property() ?

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

You don't iterate the CLR type's properties. Instead iterate the Model's Entities' Properties, which have a reference to the CLR PropertyInfo, but also are the right place to configure the column name mapping.

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM