【问题标题】:mongodb data losing when run web service in c#在c#中运行Web服务时mongodb数据丢失
【发布时间】:2021-08-09 14:53:50
【问题描述】:

我有一个实体类

public class City
{
    [BsonId]
    public string id { get; set; }
    public int value { get; set; }        
}

我创建了一个 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;
        }
    }

当我运行服务时,我得到了那个错误:

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.

我该如何解决这个问题? 感谢您的帮助。

【问题讨论】:

  • 更改字段 public int value { get;放; } to public double value { get;放; }
  • @ToanNguyen 感谢您的回答。我更改了属性类型和服务不抛出异常。

标签: c# linq web-services mongodb


【解决方案1】:

您通常不希望您的模型知道或关心它是如何存储的,因此在其上添加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
    ))
 );

source

【讨论】:

  • 它有效,我用它来规避使用双精度而不是小数的错误模型,将它添加到处理器允许它继续而不转换旧数据,至少直到我们不需要数据了,这是一个很好的解决方案
  • 这样一段代码可以放在哪里?它看起来是静态的,但是进入像启动文件这样的东西是有意义的,对吧?假设它在应用程序的整个生命周期都是全局性的。
  • Alec 是的,它是全球性的。我倾向于在您的存储库中使用静态构造函数,因为它将所有 MongoDB 内容保存在一个地方,但如果该类是通用的,我会使用 Startup。
  • 您在参数上的 cmets 方法错误。 allowOverflow 是第一个,allowTruncation 是第二个。 (对照 MongoDB C# Driver 2.12 检查)
【解决方案2】:

您是否尝试在City 类中为您的属性设置AllowTruncation=true

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

How do I set the serialization options for the geo values using the official 10gen C# driver?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    相关资源
    最近更新 更多