rbeauchamp / Swashbuckle.OData

Extends Swashbuckle with OData v4 support!
Other
128 stars 96 forks source link

SchemaRegistryExtensions.GetPropertyNameForEdmModel returns wrong Edm Property name #174

Closed KDet closed 6 years ago

KDet commented 6 years ago

I've faced to the following problem: GetPropertyNameForEdmModel retrieves name of EDM property from DataMemberAttribute if it exists.

private static string GetPropertyNameForEdmModel(MemberInfo currentProperty, IEdmNamedElement edmProperty)
{
    Contract.Requires(currentProperty != null);
    Contract.Requires(edmProperty != null);
    var dataMemberAttribute = currentProperty.GetCustomAttributes<DataMemberAttribute>()?.SingleOrDefault();
    return !string.IsNullOrWhiteSpace(dataMemberAttribute?.Name) ? dataMemberAttribute.Name : edmProperty.Name;
}

Than that new name writes to properties list of schema definition. In case if new name (from DataMemberAttribute) is not same to the type's property name, this code in method ApplyEdmModelPropertyNamesToSchema thew exception

...
foreach (var property in schemaDefinition.properties)
{
    var currentProperty = type.GetProperty(property.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); 
//currentProperty = null because type doesn't contains changed name
    var edmPropertyName = GetEdmPropertyName(currentProperty, edmType); 
//GetEdmPropertyName calls GetPropertyNameForEdmModel  internally
...
}

Question: Why does any logic have to override names of already setup-ed? Why there is a dependency only on DataMemberAttribute (not to JsonPropertyAttribute)?

Could it be a possible fix is?

private static string GetPropertyNameForEdmModel(MemberInfo currentProperty, IEdmNamedElement edmProperty)
{
    Contract.Requires(currentProperty != null);
    Contract.Requires(edmProperty != null);
    return edmProperty.Name;
}
KDet commented 6 years ago

Fixed by providing Custom Property Resolver #176

rbeauchamp commented 6 years ago

Resolved in https://www.nuget.org/packages/Swashbuckle.OData/3.5.0. Thanks @KDet!