Search code examples
c#linqentity-framework-coreincludedatabase-relations

C# Entity Framework Core: how do I get the relationship of the bill to the vendor without including the vendor's list of bills?


I am trying to exclude a relationship from a database query using linq in Entity Framework Core.

I have a database where I have a table of Bills and a table of Vendors.

  • Each Bill has 1 Vendor
  • Each Vendor has many Bills

I want to exclude the List<Bill> from the Vendor while maintaining the Vendor information for the Bill I am querying. So I can gather Vendor information from that specific Bill. I currently have the relation as below.

foundBills = db_context.Bills.Include(v => v.Vendor).Where(searchLambda).ToList();

Is there a .Exclude or .Intersect or something that I am missing to exclude the circular relationship? It is using way too much memory.


Solution

  • If you configured your Bill and Vendor Model classes correctly for "One to Many" relationship, they should look like this:

    public class Vendor
    {
        // ... other properties
    
        public Bill Bill { get; set; }
    }
    
    public class Bill
    {
        // ... other properties
    
        public ICollection<Vendor> Vendors { get; set; }
    }
    

    With this logic, there shouldn't be any circular dependency, because this is how it works.

    Later you can use Include or not, but if you want to not have a Bill information in your Vendor for the final output then create separate models for Vendor and Bill:

    public class BillOutput
    {
        public List<VendorOutput> Vendors { get; set; }
    }
    
    
    public class VendorOutput
    {
        // ... other properties
    }
    

    and later:

    var finalOutput = db_context.Bills.Include(v => v.Vendor).Where(searchLambda).
                          Select(items => new BillOutput
                          {
                              Vendors = items.Select(item => new VendorOutput
                              {
                                  // here you don't have the Bill Information
                              }
                          } )
                         .ToList();