C#mongoDB数据采集

时间:2017-04-15 14:35:13

标签: c# mongodb

人。 马上抱歉我的英语。 我需要帮助解决我自己几天无法决定的问题。

我有一个与mongoDB相关的C#项目。 用户可以创建一个帐户并为他创建两个字符。

这里是角色创作:

Character.Character character = new Character.Character
  {
    SocialClubName = player.socialClubName,
    Name = name,
    Surname = surname,
    RegistrationDate = DateTime.Now,
    LastLoginDate = DateTime.Now,
    RegistrationIp = player.address,
    CurrentIp = player.address
  };

  Characters.InsertOneAsync(character);

Character.cs

  public class Character
  {
    [BsonId]
    public ObjectId Id { get; set; }

    public string SocialClubName { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }    
    public string RegistrationIp { get; set; }
    public string CurrentIp { get; set; }
    public DateTime RegistrationDate { get; set; }
    public DateTime LastLoginDate { get; set; }
  }

问题是从数据库中获取这些数据。我需要有两个字符数据的全局变量。

现在看起来像这样:

public static string Name { get; set; }
public static string Surname { get; set; }
public static string RegistrationIp { get; set; }
public static string CurrentIp { get; set; }
public static DateTime RegistrationDate { get; set; }
public static DateTime LastLoginDate { get; set; }

public static async Task LoadCharacterData(Client player)
{
  var filter = new BsonDocument("NameOfTable", player.name);
  var characters = await DatabaseManager.Characters.Find(filter).ToListAsync();

  foreach (var character in characters)
  {
    Name = character.Name;
    Surname = character.Surname;
    RegistrationIp = character.RegistrationIp;
    CurrentIp = character.CurrentIp;
    RegistrationDate = character.RegistrationDate;
    LastLoginDate = character.LastLoginDate;
  }
}

看起来很愚蠢,因为我刚刚开始使用C#。我决定使用MongoDB,因为我之前使用过MeteorApp。

1 个答案:

答案 0 :(得分:0)

每次阅读时,您的示例都会覆盖名称/ SurName等,因此您只会检索最后一个字符。

您可以创建一个User类并获取这些内容,如下所示:

public class User 
{
  public string Name{get;set;}
  public string SurName{get;set;}
}

public static List<User> Users {get;set;}
public static async Task LoadCharacterData(Client player)
{
  //*Snip*
  foreach(var character in character)
    Users.Add(new User {Name = character.Name; SurName = character.Surname;}
}