Mongodb C#,用接口查询

时间:2014-05-08 18:14:09

标签: c# mongodb interface

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

 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));

    }

}

存在问题功能

 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;
    }

然后在启动时关注代码:

//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

然后它说“附加信息:无法确定表达式的序列化信息:e.Id。”在函数FindById行

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);

它工作正常。

问题是不想在这个函数中使用multiply if语句,我想使用漂亮,干净的界面。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

使用T:

交换IObjectWithID
 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;
    }