在mongodb集合上无法做到这一点

时间:2014-06-12 00:50:16

标签: c# .net linq mongodb mongodb-.net-driver

我有两个模型,一个是用户和一个团队,如下所示:

    [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

2 个答案:

答案 0 :(得分:11)

您缺少名称空间MongoDB.Driver.Linq,只需将其添加到顶部:

using MongoDB.Driver.Linq;

具体方法是:

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

答案 1 :(得分:2)

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