entity framework - Why is Automapper.ProjectTo() throwing a null reference exception? -


i have mapping:

var config = new mapperconfiguration(cfg => {     cfg.createmap<foo, foodto>()         .formember(dest => dest.id,             opt => opt.mapfrom(src => src.id))         .formember(dest => dest.name,             opt => opt.mapfrom(src => src.name))         .formember(dest => dest.phonenumber,             opt => opt.mapfrom(src => src.phonenumbers.number)) //etc. }); 

and i'm trying use in unit test calling mocked ef objects:

var ids = new list<string>()     {         "123";         "456";         "789";     }; var data = new list<foo>(); foreach(var id in ids) {     data.add(new foo() { id = id }); }  this.mockcontext = new mock<entities>(); this.mockset = new mock<dbset<foo>>(); this.mockset.as<iqueryable<foo>>().setup(p => p.provider).returns(data.provider); this.mockset.as<iqueryable<foo>>().setup(p => p.expression).returns(data.expression); this.mockset.as<iqueryable<foo>>().setup(p => p.elementtype).returns(data.elementtype); this.mockset.as<iqueryable<foo>>().setup(p => p.getenumerator()).returns(data.getenumerator()); 

when query entities directly:

var id = "123"; var bar = this.mockcontext.object.foo.where(p => p.id == id); 

i iqueryable() single result, expected. when try project object dto:

var id = "123"; var buzz = this.mockcontext.object.foo.where(p => p.id == id).projectto<foodto>(this.config); 

the iqueryable throws null reference exception if try access results in way. example:

buzz.tolist(); buzz.singleordefault(); // mirrors actual call in code since getbyid query. 

both fail. missing here?

the problem lies foo uses ef navigation properties refer other objects. phonenumber in instance. since test data created without linked phonenumber object, breaks inside of projectto method. isn't problem when grabbing top level queryable directly, automapper needs objects exist (even if they're empty) in order complete mapping. changing line to:

data.add(new foo() { id = id, phonenumber = new phonenumber() }); 

allows projectto method complete, albeit null values.


Comments