在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 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 { get; set; } 

所以我创建了一个用户,但现在我想向我的用户添加团队。 这是我正在使用的代码:

  var databaseClient = new MongoClient(Settings.Default.FantasySportsConnectionString); var server = databaseClient.GetServer(); var database = server.GetDatabase("Users"); var collection = database.GetCollection("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' to 'System.Collections.IEnumerable'

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

你缺少一个命名空间, MongoDB.Driver.Linq ,只需在顶部添加:

 using MongoDB.Driver.Linq; 

具体方法是:

 LinqExtensionMethods { public static IQueryable AsQueryable(this MongoCollection collection); //... } 

我在使用.NET驱动程序v2.3.0时遇到了同样的错误。 我删除了它并使用NuGet安装了v2.2.4并且它工作正常。 我一直得到的错误:找不到方法:’MongoDB.Driver.Linq.IMongoQueryable 1 MongoDB.Driver.IMongoCollectionExtensions.AsQueryable(MongoDB.Driver.IMongoCollection 1)’。

你需要包括

 using MongoDB.Driver.Linq;