Asked a question earlier, but I didn't word it well enough. I need to access property names in a Mongo db builders projection instantiation.
Versus coding out every single possibility I wanted to access the property via a user choice. Like this
UserSubmittedModel s = new UserSubmittedModel
{
SensorDataChannelName = "AirTemp"
};
var projection = Builders<SensorData>.Projection.Include(u => u.GetType().GetProperty(s.SensorDataChannelName).GetValue(u, null)).Include(u => u.MainFileId).Include(u => u.UnixTime).Exclude(u => u.Id);
However, I repeatedly run into this error when I do this
System.InvalidOperationException: 'Unable to determine the serialization information for u => u.GetType().GetProperty(value(Program <>c__DisplayClass0_1).s.SensorDataChannelName).GetValue(u, null).'
I've also looked deeply at another post involving this where they return from a method, essentially the same thing. But I get the same results.
static object GetPropValue(object target, string? propName)
{
return target.GetType().GetProperty(propName).GetValue(target, null);
}
I want convert a user selection into the model param name, so I can project and include it.
CodePudding user response:
From previous question, I think that you are trying to get the property name from SensorData
based on the selected value (s.SensorDataChannelName
).
From the MongoDB .NET Driver documentation (Projection Definition Builder section), you can pass the field name as string
, which is an alternative to the lambda expression.
var projection = Builders<Widget>.Projection.Include("X")
.Include("Y")
.Exclude("Id");
With this line:
u.GetType().GetProperty(s.SensorDataChannelName).GetValue(u, null)
It returns the value of u./* value of s.SensorDataChannelName */
but not the property (name) in u
.
Either you can straight pass the field name as below:
var projection = Builders<SensorData>.Projection
.Include(s.SensorDataChannelName)
// Following fields to be included / excluded
;
Or if you want to validate the property name first:
string fieldName = typeof(SensorData).GetProperty(s.SensorDataChannelName)?.Name;
if (String.IsNullOrEmpty(fieldName))
{
// TO-DO Handle Invalid field name
return;
}
var projection = Builders<SensorData>.Projection
.Include(fieldName)
.Include(u => u.MainFileId)
.Include(u => u.UnixTime)
.Exclude(u => u.Id);