I am fairly new to mongodb and I am trying to query a collection with byte property but I am getting an invalid cast exception. To summarize,
public class MongoDbAddressCollection
{
private IMongoCollection<Addresses> collection = database.GetCollection<Addresses>("AddressCollection");
public IEnumerable<Addresses> Where(System.Linq.Expressions.Expression<Func<Addresses, bool>> filter = null)
{
var items = collection.AsQueryable().Where(filter);
if (items == null)
return null;
return items.ToList();
}
}
public class Test
{
public void DoSomthingWithAddresses()
{
MongoDbAddressCollection addressCollection=new MongoDbAddressCollection();
//exception occurs in MongoDbAddressCollection.Where method when executing the ToList().
List<Addresses> homeAddresses=addressCollection.Where(x=>x.AddressType==(byte)EnumAddressType.HomeAddress);
foreach(var address in homeAddresses)
{
//do stuff
}
}
}
And the address entity is as following class
public class Address
{
public Guid UserId { get; set; }
public string Street { get; set; }
public byte AddressType { get; set; }
.....
}
public enum EnumAddressType
{
HomeAddress=1,
WorkAddress=2
}
Actually the issue seems to be a type mismatch between mongodb and .net, I can see that the AddressType for WorkAddress entities is 10 which is binary representation of 2. But, I cannot think of a solution other than changing all byte properties in all of our entities to int before I insert them to collections (we have lots of byte properties in different entities)... Or can this be fixed with a workaround in the query (linq where condition)?
Thanks in advanced.