Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support indexers in expression trees when generating PropertyChain for simple cases. #2057

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/FluentValidation.Tests/PropertyChainTests.cs
Expand Up @@ -83,6 +83,13 @@ public class PropertyChainTests {
chain.ToString().ShouldEqual("Address.Id");
}

[Fact]
public void Creates_from_expression_with_indexer() {
Expression<Func<Person, string>> expr = x => x.Orders[0].ProductName;
var chain = PropertyChain.FromExpression(expr);
chain.ToString().ShouldEqual("Orders[0].ProductName");
}

[Fact]
public void Should_ignore_blanks() {
chain.Add("");
Expand Down
25 changes: 23 additions & 2 deletions src/FluentValidation/Internal/PropertyChain.cs
Expand Up @@ -70,10 +70,31 @@ public class PropertyChain {
});

var memberExp = getMemberExp(expression.Body);
string indexer = null;

while(memberExp != null) {
memberNames.Push(memberExp.Member.Name);
memberExp = getMemberExp(memberExp.Expression);
string propertyName = memberExp.Member.Name;

if (indexer != null) {
propertyName += "[" + indexer + "]";
indexer = null;
}

memberNames.Push(propertyName);

// Handle indexers.
if (memberExp.Expression is MethodCallExpression mce) {
if (mce.Method is {IsSpecialName: true, Name: "get_Item"} && mce.Arguments.Count == 1 && mce.Arguments[0] is ConstantExpression ce) {
memberExp = getMemberExp(mce.Object);
if (memberExp != null) {
indexer = ce.Value?.ToString();
}
}
}
else {
memberExp = getMemberExp(memberExp.Expression);
}

}

return new PropertyChain(memberNames);
Expand Down