cannot do asqueryable on mongodb collection

时间秒杀一切 提交于 2019-12-08 16:58:58

问题


I got two models, a User and a Team as below:

    [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; }

So I've created a user but now I want to add teams to my user. This is the code I'm using:

  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" });

But when I do this I get these errors:

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


回答1:


You are missing a namespace, MongoDB.Driver.Linq, simply add that at the top:

using MongoDB.Driver.Linq;

That specific method is:

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



回答2:


I was getting the same error with with the .NET driver v2.3.0. I removed it and installed v2.2.4 using NuGet and it worked. The error I kept getting: Method not found: 'MongoDB.Driver.Linq.IMongoQueryable1<!!0> MongoDB.Driver.IMongoCollectionExtensions.AsQueryable(MongoDB.Driver.IMongoCollection1)'.



来源:https://stackoverflow.com/questions/24174897/cannot-do-asqueryable-on-mongodb-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!