泛型类型<tgen>其中TGen:SomeType不能使用表达式树匹配SomeType

时间:2016-06-11 15:20:16

标签: c# mongodb mongodb-.net-driver expression-trees

我有一个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

周围有优雅的方式吗?

0 个答案:

没有答案