Skip to content

Commit

Permalink
Merge pull request #11 from aditnryn/read-member-attr
Browse files Browse the repository at this point in the history
Read the AttributeLogicalNameAttribute on members
  • Loading branch information
MscrmTools authored Jan 15, 2024
2 parents fee51d7 + c771629 commit a4bdaba
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions MscrmTools.Shared/Helpers/AnonymousTypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public static string[] GetAttributeNamesArray<T>(Expression<Func<T, object>> ano
var unaryInitialiazer = anonymousTypeInitializer.Body as UnaryExpression;

if (newInitializer?.Members == null && memberInitializer?.Member == null && unaryInitialiazer?.Operand == null)

{
throw new ArgumentException("lambda must return an object initializer");
}
Expand All @@ -35,11 +34,11 @@ public static string[] GetAttributeNamesArray<T>(Expression<Func<T, object>> ano
}
else if (memberInitializer?.Member != null)
{
return new string[] { memberInitializer?.Member.Name.ToLower() };
return new string[] { GetLogicalAttributeName<T>(memberInitializer?.Member) };
}
else
{
return new string[] { ((MemberExpression)unaryInitialiazer?.Operand).Member.Name.ToLower() };
return new string[] { GetLogicalAttributeName<T>(((MemberExpression)unaryInitialiazer?.Operand).Member) };
}
}

Expand All @@ -62,9 +61,14 @@ public static string GetAttributeName<T>(Expression<Func<T, object>> anonymousTy
throw new ArgumentException("lambda must return an object initializer");
}

// Search for and replace any occurence of Id with the actual Entity's Id
var attr = memberExp.Member.GetCustomAttribute<AttributeLogicalNameAttribute>();

if (attr == null)
{
throw new ArgumentException(memberExp.Member.Name + "does not contain an AttributeLogicalNameAttribute. Unable to determine logical name");
}

return memberExp.Member.Name.ToLower();
return attr.LogicalName;
}

/// <summary>
Expand All @@ -75,20 +79,14 @@ public static string GetAttributeName<T>(Expression<Func<T, object>> anonymousTy
private static string GetLogicalAttributeName<T>(MemberInfo property) where T : Entity

{
var name = property.Name.ToLower();
if (name == "id")
{
var attribute = typeof(T).GetProperty("Id")?.GetCustomAttributes<AttributeLogicalNameAttribute>().FirstOrDefault();

if (attribute == null)
{
throw new ArgumentException(property.Name + " does not contain an AttributeLogicalNameAttribute. Unable to determine id");
}
var attribute = typeof(T).GetMember(property.Name).First().GetCustomAttribute<AttributeLogicalNameAttribute>();

name = attribute.LogicalName;
if (attribute == null)
{
throw new ArgumentException(property.Name + " does not contain an AttributeLogicalNameAttribute. Unable to determine logical name");
}

return name;
return attribute.LogicalName;
}
}
}

0 comments on commit a4bdaba

Please sign in to comment.