开发者

I can't avois this select N+1

开发者 https://www.devze.com 2023-04-13 03:17 出处:网络
I have this mapping ( it comes from adventureworks since I used it in a demo app for an automatic paging collection )

I have this mapping ( it comes from adventureworks since I used it in a demo app for an automatic paging collection )

ModelMapper mapper = new ModelMapper(开发者_如何学Gonew SimpleModelInspector());

            mapper.Class<Contact>(
                k => { 
                    k.Id(i => i.ContactID, m => m.Generator(Generators.Native));
                    k.Schema("Person");
                } 
                );
            mapper.Class<Employee>(
                k => 
                {
                    k.Id(i => i.EmployeeID, m => m.Generator(Generators.Native));
                    k.Schema("HumanResources");
                    k.ManyToOne(c => c.Contact, m =>  m.Column("ContactID"));
                }
                );
            mapper.Class<SalesOrderHeader>(
                k =>
                {
                    k.Id(i => i.SalesOrderID,m=>m.Generator(Generators.Native));
                    k.Schema("Sales");
                    k.ManyToOne(c => c.SalesPerson, m => m.Column("SalesPersonID"));
                    k.ManyToOne(c => c.Contact, m => m.Column("ContactID"));
                }
                );

            var map = mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddDeserializedMapping(map,string.Empty);

and the following ( limited ) query:

var list = NHHelper.Instance.CurrentSession.Query<SalesOrderHeader>()
                            .Fetch(k => k.Contact)
                            .Fetch(k => k.SalesPerson)
                            .Skip(first)
                            .Take(count)
                            .ToList();

I can't remove the select N+1 caused by employee-contact, how can I do ? Consider mapping too can be changed !

EDIT: I add the working solution by @cremor

 var list = NHHelper.Instance.CurrentSession.Query<SalesOrderHeader>()
                            .Fetch(k => k.Contact)
                            .Fetch(k => k.SalesPerson).ThenFetch(k=>k.Contact)
                            .Skip(first)
                            .Take(count)
                            .ToList();

this will avoid the problem.


Adding .ThenFetch(c => c.Contact) after .Fetch(k => k.SalesPerson) should also fetch the Contact of the Employee.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号