2014-06-12 41 views
7

做AsQueryable已我有兩個型號,用戶和下方的團隊:不能在MongoDB中收集

[BsonRepresentation(BsonType.ObjectId)] 
    public ObjectId _id { get; set; } 
    [Display(Name = "Password:")] 
    public string Password { get; set; } 
    [Display(Name = "Confirm:")] 
    public string ConfirmPassword { get; set; } 
    [Display(Name = "Email:")] 
    public string Email { get; set; } 
    [Display(Name = "Username:")] 
    public string UserName { get; set; } 
    [Display(Name = "Firtname:")] 
    public string Firstname { get; set; } 
    [Display(Name = "Lastname:")] 
    public string Lastname { get; set; } 
    [Display(Name = "Country:")] 
    public string Country { get; set; } 
    [Display(Name = "City:")] 
    public string City { get; set; } 
    [Display(Name = "Birthdate:")] 
    public int Birthdate { get; set; } 
    public List<Team> Teams { get; set; } 


    [BsonRepresentation(BsonType.ObjectId)] 
    public ObjectId TeamID { get; set; } 
    public string TeamName { get; set; } 
    public string UserName { get; set; } 
    public int LeagueID { get; set; } 

    public List<Player> Player { get; set; } 

所以我創建了一個用戶,但現在我想球隊添加到我的用戶。 這是我使用的代碼:

var databaseClient = new MongoClient(Settings.Default.FantasySportsConnectionString); 
    var server = databaseClient.GetServer(); 
    var database = server.GetDatabase("Users"); 
    var collection = database.GetCollection<User>("users"); 

    var user = collection.AsQueryable().First(o => o._id == Session["ID"]); 

    user.Teams.Add(new Team { TeamID = new ObjectId(), TeamName = "Some Team" }); 

但是當我這樣做,我得到這些錯誤:

1:Instance argument: cannot convert from 'MongoDB.Driver.MongoCollection<SportsFantasy_2._0.Models.User>' to 'System.Collections.IEnumerable'

2:'MongoDB.Driver.MongoCollection<SportsFantasy_2._0.Models.User>' does not contain a definition for 'AsQueryable' and the best extension method overload 'System.Linq.Queryable.AsQueryable(System.Collections.IEnumerable)' has some invalid arguments

+0

'AsQueryable'是'擴展方法IEnumerable ''不是你MongoCollection'將創建一個或可能存在的蒙戈一個LINQ擴展類已經 –

回答

9

你缺少一個命名空間,MongoDB.Driver.Linq,只需在頂部加上:

using MongoDB.Driver.Linq; 

那具體方法是:

LinqExtensionMethods 
{ 
    public static IQueryable<T> AsQueryable<T>(this MongoCollection<T> collection); 
    //... 
} 
+0

我加該但現在它說: 錯誤\t \t 1操作員「==」不能被應用於類型「MongoDB.Bson.ObjectId」和「對象」 \t 就行變種用戶的操作數= collection.AsQueryable()首先。 (o => o._id == Session [「ID」]); –

+2

@DanielGustafsson完全不同的問題。確實_id是ObjectID,Session [「ID」]是一個對象。如果你確定它實際上是一個ObjectID,那麼將它轉換爲:o._id ==(ObjectID)Session [「ID」] – i3arnon

1

我得到了同樣的錯誤與使用.NET驅動程序V2.3.0。我刪除它,並使用NuGet安裝v2.2.4,它工作。我一直得到的錯誤: 未找到方法:'MongoDB.Driver.Linq.IMongoQueryable 1<!!0> MongoDB.Driver.IMongoCollectionExtensions.AsQueryable(MongoDB.Driver.IMongoCollection 1)'。

+0

當我升級到2.3.0時,我得到了同樣的錯誤,並且我改回到2.2。 4,它再次運作。可能是2.3.0版本的錯誤。 – zhimin

0

你需要包括

using MongoDB.Driver.Linq;