Reputation: 447
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)
Upvotes: 0
Views: 936
Reputation: 89386
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);
}
}
Upvotes: 2