mongodb c#,查询带接口

本文关键字:接口 查询 mongodb | 更新日期: 2023-09-27 18:02:38

我有以下问题:这是我的界面:

 public interface IObjectWithID
{
    ObjectId Id { get; set; }
}
我对象:

public class Order : IObjectWithID
{
    [BsonId]
    public ObjectId Id
    {
        get;
        set;
    }
    private Customer customer;
    public Customer Customer
    {
        get { return customer; }
        set { customer = value; }
    }
    public Employees employee;
    private Employees Employee
    {
        get { return employee; }
        set { employee = value; }
    }
    public IList<Product> Products = new List<Product>();
    public Order(Customer customer, Employees employee, params Product[] product)
    {
        this.customer = customer;
        this.employee = employee;
        TabelaPosredniaKlientOrder.Tabela.Add(new ObiektPosredniKlientOrder(this.Id, Customer.Id));
        TabelaPosredniaPracownikOrder.Tabela.Add(new ObiektPosredniPracownikOrder(this.Id, Employee.Id));
    }
}

there is problem function

 public static IObjectWithID FindById<T>(MongoCursor cursor, ObjectId id) where T: IObjectWithID
    {
        var query = Query<IObjectWithID>.Where(e => e.Id == id);
        var item = cursor.Collection.FindOneAs<IObjectWithID>(query);
        return item;
    }

then在启动时的代码如下:

//database initialization code
// collection initialization code
var neworder = new order(param1, param2, param3);
collection.Inser(neworder); //everything fine
var item = FindByID<Order>(cursor, neworder.Id); //cursor is initializated

然后在

行的FindById函数中显示"附加信息:无法确定表达式的序列化信息:e.Id "
var query = Query<IObjectWithID>.Where(e => e.Id == id);

但是当我把它转换成:

var query = Query<Order>.Where(e => e.Id == id);
var item = cursor.Collection.FindOneAs<Order>(query);

它工作得很好。

问题是不想在这个函数中有乘法if语句,我想使用漂亮,干净的接口。

提前感谢!

mongodb c#,查询带接口

交换IObjectWithID与T:

 public static IObjectWithID FindById<T>(MongoCursor cursor, ObjectId id) where T: IObjectWithID
    {
        var query = Query<T>.Where(e => e.Id == id);
        var item = cursor.Collection.FindOneAs<T>(query);
        return item;
    }