2017-04-12 361 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

相關問題