あなたは、このソリューション
public Interface IEntity
{
int Id {set ;get}
}
class EntryManagement<T> where T : IEntity
{
public T GetEntry(ObjectId id)
{
IMongoCollection<T> collections = db.GetCollection<T>(database);
var getObj = collections.Find(x => x.Id == id).FirstOrDefault();
return getObj;
}
}
のためのインターフェイスを使用するか、実行時にラムダ式を動的に作成することができます
public T GetEntry(ObjectId id)
{
IMongoCollection<T> collections = db.GetCollection<T>(database);
var parameterExpression = Expression.Parameter(typeof(T), "object");
var propertyOrFieldExpression = Expression.PropertyOrField(parameterExpression, "Id");
var equalityExpression = Expression.Equal(propertyOrFieldExpression, Expression.Constant(id, typeof(int)));
var lambdaExpression = Expression.Lambda<Func<T, bool>>(equalityExpression, parameterExpression);
var getObj = collections.Find(lambdaExpression).FirstOrDefault();
return getObj;
}
よしを、私はあなたの第二の溶液を試してみましたが、それは働きました! 'int型ではなく' ObjectId'型なので 'typeof(ObjectId)'に変更するだけです。しかし、ちょうど質問。私はあなたの最初のソリューションを使用する場合、私はすべての私のモデルクラスの 'IEntity'を実装する必要がありますか? –
@CarlosMiguelColantaはい、私はあなたのモデルクラスのすべてがIEntityを実装しなければならないということを言及することを忘れています。私はハードタイプなので最初の解決策を好む。 – Kahbazi