CSharp · Console
using System;
using System.Linq;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
class Factory
{
public virtual int Id { get; set; }
}
class User
{
public virtual int Id { get; set; }
public virtual Factory Factory { get; set; }
}
class Order
{
public virtual int Id { get; set; }
public virtual int FactoryId { get; set; }
}
public class Program
{
public static void Main()
{
var client = new MongoClient("mongodb://localhost/test");
var db = client.GetDatabase("test");
BsonClassMap.RegisterClassMap<Order>(m =>
{
m.MapIdProperty(x => x.Id);
m.MapProperty(x => x.FactoryId);
});
var currentUser = new User();
//exception was throwed here
var orders = db
.GetCollection<Order>("orders").AsQueryable()
.Where(x => currentUser.Factory == null || x.FactoryId == currentUser.Factory.Id)
.ToArray();
//same exception for followed expression
/*
var orders = db
.GetCollection<Order>("orders").AsQueryable()
.Where(x => currentUser.Factory == null || (currentUser.Factory != null && x.FactoryId == currentUser.Factory.Id))
.ToArray();
*/
//no exception, all work fine
currentUser.Factory = new Factory();
orders = db
.GetCollection<Order>("orders").AsQueryable()
.Where(x => currentUser.Factory == null || x.FactoryId == currentUser.Factory.Id)
.ToArray();
}
}