Skip to content

Commit

Permalink
Fix dictionary indexes (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
fredimachado authored Aug 15, 2023
1 parent c0639da commit df8023b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions MongoDB.Entities/Builders/Index.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,17 @@ internal Key(Expression<Func<T, object?>> expression, KeyType type)
return;
}

if (expression.Body is MethodCallExpression methodCallExpression
&& methodCallExpression.Method.DeclaringType.GetGenericTypeDefinition() == typeof(Dictionary<,>)
&& methodCallExpression.Arguments.Count == 1
&& methodCallExpression.Arguments[0].Type == typeof(string)
&& methodCallExpression.Arguments[0] is ConstantExpression constantExpression
&& methodCallExpression.Object is MemberExpression memberExpression)
{
PropertyName = $"{memberExpression.Member.Name}.{constantExpression.Value}";
return;
}

PropertyName = expression.FullPath();
}
}
Expand Down
20 changes: 20 additions & 0 deletions Tests/TestIndexes.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

Expand Down Expand Up @@ -186,4 +187,23 @@ await DB.Index<Author>()
.Key(x => x.Age, KeyType.Descending)
.CreateAsync();
}

[TestMethod]
public async Task dictionary_item_index_should_use_key_value()
{
await DB.DropCollectionAsync<TestModel>();

var index = await DB.Index<TestModel>()
.Key(a => a.Metadata["AnotherKey"], KeyType.Ascending)
.Key(a => a.EndDate, KeyType.Ascending)
.CreateAsync();

Assert.AreEqual("Metadata.AnotherKey(Asc) | EndDate(Asc)", index);
}

public class TestModel : Entity
{
public DateTime EndDate { get; set; }
public Dictionary<string, object> Metadata { get; set; } = new();
}
}

0 comments on commit df8023b

Please sign in to comment.