在 C# 中运行 Web 服务时 mongodb 数据丢失

tra*_*loo 3 c# linq web-services mongodb

我有一个实体类

public class City
{
    [BsonId]
    public string id { get; set; }
    public int value { get; set; }        
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个 web 服务,并且有一个 webmethod 作为

[WebMethod]
    public List<City> linQuery()
    {
        MongoConn dao = new MongoConn();
        MongoServer mongo = dao.getConnection();
        List<City> list = new List<City>();

        string dbName = dao.dbName();
        var db = mongo.GetDatabase(dbName);

        Console.WriteLine(db);
        using (mongo.RequestStart(db))
        {
            var collection = db.GetCollection<City>("cityMap");
            IQueryable<City> cities = collection.AsQueryable().Where(c => c.value > 1200);
            foreach (City city in cities)
                list.Add(city);
            return list;
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我运行该服务时,出现该错误:

System.IO.FileFormatException: An error occurred while deserializing the value property of class WebService1.City: Truncation resulted in data loss. ---> MongoDB.Bson.TruncationException: Truncation resulted in data loss.
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?感谢您的帮助。

Cha*_*ock 7

您通常不希望您的模型知道或关心它是如何存储的,因此用MongoDB.Bson属性填充它并不理想。您可以使用此配置来配置 MongoDB.Driver 读取和存储小数的方式。

BsonSerializer.RegisterSerializer(
  typeof(decimal),
   new DecimalSerializer(BsonType.Double,
   new RepresentationConverter(
     true, // allow overflow, return decimal.MinValue or decimal.MaxValue instead
     true //allow truncation
    ))
 );
Run Code Online (Sandbox Code Playgroud)

来源


Tim*_*ang 6

AllowTruncation=trueCity课堂上有没有尝试为你的属性设置?

public class City
{
    [BsonId]
    [BsonRepresentation(BsonType.Int, AllowTruncation=true)]
    public string id { get; set; }
    [BsonRepresentation(BsonType.Int, AllowTruncation=true)]
    public int value { get; set; }        
}
Run Code Online (Sandbox Code Playgroud)

如何使用官方 10gen C# 驱动程序设置地理值的序列化选项?