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

[QUESTION] UpdateMany with Dictionary<string, object> #2519

Open
ssteiner opened this issue Jul 9, 2024 · 1 comment
Open

[QUESTION] UpdateMany with Dictionary<string, object> #2519

ssteiner opened this issue Jul 9, 2024 · 1 comment
Labels

Comments

@ssteiner
Copy link

ssteiner commented Jul 9, 2024

I'm using a lot of generics in my application - most documents have a common structure, so my generic bulk update has the document id's and a Dictionary<string, object> as input parameters. I then generate a new entity based on that dictionary, and provide it to UpdateMany.

var myDict = new Dictionary<string, object> 
{ 
    {"StringProp", "hello" },
    {"BoolProp", true },
    {"SubProp.StringProp", "subprop value" },
}
List<string> ids = []; // would contain the ids of the documents to update

TEntity updateEntity = myDict.ToObject<T>(); // implementation omitted
context.GetCollection<TEntity>().UpdateMany(x => updatEntity, u => ids);

if I run this, I get an exception telling me this:

Extend expression must return an anonymous class to be merge with entities. Eg: `col.UpdateMany(x => new { Name = x.Name.ToUpper() }, x => x.Age > 10)

So, how can I generate that anonymous class that UpdateMany requires?

@ssteiner
Copy link
Author

So I hacked something together:

var script = "{";
int propertyCount = 0;
foreach (var updatedProperty in myDict.Keys)
{
    object valueToSet = myDict[updatedProperty];
    if (valueToSet is string)
        script += $"{updatedProperty}: '{valueToSet}'";
    else
        script += $"{updatedProperty}: {valueToSet}";
    propertyCount++;
}
script += "}";
var filter = BsonMapper.Global.GetExpression<T, bool>(u => ids);
context.GetCollection<TEntity>().UpdateMany(script, filter);

I did not try this for all possible types and subproperties currently don't work. Plus, you can't set a full subobject this way either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant