2017-04-12 478 views
0

我有问题需要在C#中获取对象。我使用mongo驱动程序2.4.3。如何用c从mongodb驱动程序3.4.2获取对象#

我有这样的代码:

public Employee GetEmployee(int id) 
    { 
     IMongoCollection<Employee> collection = conectWithDatabase(); 

     var filter = Builders<Employee>.Filter.Eq("EmployeeId", id); 
     var obtenido = collection.Find(filter).First(); 

     return obtenido; 
    } 

public List<Employee> GetAllEmployees() 
    { 
     IMongoCollection<Employee> collection = conectWithDatabase(); 
     var query = from employee in collection.AsQueryable<Employee>() 
        select employee; 
     return query.ToList(); 
    } 

在第一个代码时,我打电话GetEmplyee方法的程序显示此异常

System.InvalidOperationException: 'No se pueden crear las instancias de 
    clases abstractas.' -> in this line collection.Find(filter).First(); 

而在第二代码程序显示相同的异常,当我尝试将查询var列表。

我尝试从MongoDB获取对象,如果有人可以帮助我,我将不胜感激。 对不起,我的英语不好。

public abstract class Employee 
{ 
    public int EmployeeId { get; set; } 
    public string Name { get; set; } 
    public DateTime StartDate { get; set; } 
} 

public class FullTimeEmployee : Employee 
{ 
    public int Salary { get; set; } 
} 

public class PartTimeEmployee : Employee 
{ 
    public double HourlyRate { get; set; } 
} 
+0

你的例外是“无法创建抽象类的实例”。所以最可能的是Employee类被声明为抽象类。请说明这个类的声明? – JleruOHeP

+0

是员工是抽象的我有FullTimeEmployee和PartTimeEmployee。但是我不知道数据库让我工作的Employee类型。我更新了问题 @JleruOHeP – nicoperez

+0

请看看这里http://mongodb.github.io/mongo-csharp-driver/2.4/reference/bson/mapping/polymorphism/ – Veeram

回答

0

在一个基本的层次上..你需要映射鉴别器列,然后匹配类型的基础上。

驱动程序应该能够为你做这个

Inheritance in MongoDb: how to request instances of defined type

+0

这个问题,我不知道查询结果中数据库给我的Employee类型。 – nicoperez

+0

然后映射一个鉴别器列并与nameof(typeof类)匹配,然后投射 – Mardoxx

+0

OK。 Bue问题,我不能带走员工,我尝试在链接中实现代码作为示例,这是行不通的。我不能让员工去施放它。 – nicoperez

相关问题