Base solution for your next web application
Ends in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How to get an object without foreign key related object #112


User avatar
0
lcyhjx created

I define a domain entity as following: public class Order : FullAuditedEntity<long, User>
{

    public string OrderNumber { get; set; }
…

}

I have a service method in application layer as below: public InitReceiveOrderOutput InitReceiveOrder(InitReceiveOrderInput input) { Order order1 = _orderRepository.GetAll() .Include(x=>x.CreatorUser) .FirstOrDefault(x=>x.Id == input.OrderId);

        Order order2 = _orderRepository.GetAll()
           .FirstOrDefault(x => x.Id == input.OrderId);

        return new InitReceiveOrderOutput(order);
    }

After execute Order order1 = _orderRepository.GetAll() .Include(x=>x.CreatorUser) .FirstOrDefault(x=>x.Id == input.OrderId); I would like to get order with CreateUser

After execute Order order2 = _orderRepository.GetAll() .FirstOrDefault(x => x.Id == input.OrderId); I would like to get order without CreateUser

But actually, I found both order1 and order2 with CreateUser, I am not sure why? Do you have any suggestion to get order without CreateUser?


4 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    This is relate to EntityFramework.

    It uses Lazy Load. Iif you even don't Include a navigation property, it's lazy loaded from database when you acces to this property (CreatorUser in your case).

    So, there is no problem actually, if you don't access to CreatorUser, it will not be retrieved.

  • User Avatar
    0
    lcyhjx created

    Got it. Thanks your clarification!

  • User Avatar
    0
    omital created

    hi. you use include extension method in application layer. Is this true solution to Add reference to EntityFramework.dll in Application layer? or we must add a method to repository for load data with related entities, for example

    public IQuariable<Person> GetPersonWithRelatedObject(){
     return GetAll().Include(p=>p.RelatedObject);
    }
    
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    If you will not change EntityFramework later, you can add a reference to the .Application project (I do it for my projects). Otherwise, you can not also use async extensions like ToListAsync() for IQueryable, because it's only supported by EF, not supported by NHibernate for example.