我有一个Encounter
类型和一个继承它的Response
:
[BsonKnownTypes(typeof(Request), typeof(Response))]
public abstract class Encounter {
public ObjectId Id { get; set; }
}
// .. some more Encounter subtypes ...
public class Response : Encounter {
public bool IsResponded;
}
我希望能够将Encounter
或其子类型传递给Db.UpdateEncounterAsync()
方法:
class Db {
private IMongoCollection<Encounter> EncounersCollection;
// ... stuff ...
public Db() {
EncounersCollection = InitCollection();
}
// ... stuff ...
public async Task UpdateEncounterAsync<TEncounter, TField>(
TEncounter encounter, Expression<Func<TEncounter, TField>> fieldFuncExpr)
where TEncounter : Encounter
{
var value = fieldFuncExpr.Compile()(encounter);
var updateDefinition = Builders<Encounter>.Update
.Set(fieldFuncExpr, value); // Error CS1503
var updateResult = await EncounersCollection.UpdateOneAsync(
e => e.Id == encounter.Id, updateDefinition);
}
}
以下列方式:
Response response = GetResponse();
response.IsResponded = true;
// update just the IsResponded field of the response object:
UpdateEncounterAsync(response, r => r.IsResponded);
但我的UpdateEncounterAsync
没有编译:
Error CS1503 Argument 1: cannot convert from 'System.Linq.Expressions.Expression<System.Func<TEncounter, TField>>' to 'MongoDB.Driver.FieldDefinition<DataModel.Encounter, TField>'
这是因为fieldFuncExpr
的类型为Expression<Func<TEncounter, TField>>
,where TEncounter : Encounter
,但Builders<Encounter>.Update.Set(expr, value)
期望expr
类型Expression<Func<Encounter, TField>>
而不是通用TEncounter
。
周围有优雅的方式吗?