使用C#LINQ驱动程序比较Mongodb中的日期 [英] Comparing dates in Mongodb with C# LINQ driver
问题描述
我有一个 MongoDB 集合,其中包含一个表示日期的字符串字段.在我的C#应用程序中,我将结果映射到带有聚合字段的类,该字段将该字符串转换为DateTime对象
I have a MongoDB collection with a string field representing a date. In my C# app I map the results to a class with an aggregate field that convert that string to a DateTime object
[BsonIgnoreExtraElements]
public class Tweet
{
public ObjectId Id { get; set; }
[BsonElement("text")]
public string Texto { get; set; }
[BsonElement("created_at")]
public string Fecha { get; set; }
public DateTime FechaConvertida
{
get
{
var formato = "ddd MMM dd HH:mm:ss zzzz yyyy"; //'Sun Oct 23 19:42:04 +0000 2016'
var enUS = new CultureInfo("en-US");
var fechaConvertida = DateTime.ParseExact(this.Fecha, formato, enUS, DateTimeStyles.None);
return fechaConvertida;
}
}
}
然后在我的api上进行查询以过滤两个日期之间的元素(使用"CSharp驱动程序LINQ")
Then on my api I make a query filtering elements between two dates (using 'CSharp Driver LINQ')
public IEnumerable<Tweet> GetTweetsDePeriodo(string nombreColeccion, int dias)
{
var hoy = DateTime.Today;
var fechaInicial = hoy.AddDays(-dias);
var coleccion = _db.GetCollection<Tweet>(nombreColeccion).AsQueryable<Tweet>();
var tweetsFiltrados = (from c in coleccion
where c.FechaConvertida >= fechaInicial
select c
).ToList();
return coleccion;
}
然后出现以下错误: *处理请求时发生未处理的异常.InvalidOperationException:{document}.不支持FechaConvertida
有什么主意吗?预先感谢,
Any idea? Thanks in advance,
推荐答案
最后,我找到了一种针对日期字段使用自定义序列化程序的解决方案.看起来就是这样.
Finally I've found a solution using a custom serializer for the Date field. This is how it looks like.
我的课:
[BsonIgnoreExtraElements]
public class Tweet
{
public ObjectId Id { get; set; }
[BsonElement("text")]
public string Texto { get; set; }
[BsonElement("created_at")]
[BsonSerializer(typeof(FechaTweetsSerializer))]
public DateTime Fecha { get; set; }
}
还有我的自定义序列化器:
And my custom serializer:
public class FechaTweetsSerializer : SerializerBase<DateTime>
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
{
context.Writer.WriteString(value.ToString(CultureInfo.InvariantCulture));
}
public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var fecha = context.Reader.ReadString();
return ConvertirFecha(fecha);
}
private DateTime ConvertirFecha(string fechaFormatoTwitter)
{
var formato = "ddd MMM dd HH:mm:ss zzzz yyyy"; //'Sun Oct 23 19:42:04 +0000 2016'
var enUS = new CultureInfo("en-US");
var fechaConvertida = DateTime.ParseExact(fechaFormatoTwitter, formato, enUS, DateTimeStyles.None);
return fechaConvertida;
}
}
希望它对某人有帮助.
这篇关于使用C#LINQ驱动程序比较Mongodb中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!