How to add a where clause to an included object in EF?

I have three tables

  • Table of persons (table of common persons)
  • Customer table (each customer is a person)
  • Address table (each client has an address)

I need to query a database from an entity framework to match a person’s name and city, state. This is what I have, but it does not work unless I remove the state and city from the where clause

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer.tbl_Address)
    .Where(t => t.VendorID == person.VendorID &&
                t.FirstName == person.FirstName &&
                t.LastName == person.LastName &&
                t.tbl_Customer.tbl_Address.State == address.State &&
                t.tbl_Customer.tbl_Address.City == address.City).ToList();

Any help would be appreciated - I'm still pretty new to EF. As stated in my comments below, the error I am getting is

Additional Information: It is not possible to create an object of type 'System.Linq.Expressions.FieldExpression' for input of type 'System.Linq.Expressions.ParameterExpression'.

+4
2
var customer = db.tbl_Person
    .Include(t => t.tbl_Customer.tbl_Address)
    .Where(t => t.VendorID == person.VendorID &&
                t.FirstName == person.FirstName &&
                t.LastName == person.LastName)
    .ToList()
    .Where(t => t.tbl_Customer?.tbl_Address != null &&
                t.tbl_Customer.tbl_Address.State == address.State &&
                t.tbl_Customer.tbl_Address.City == address.City).ToList();

, , . , , .

EDIT: ToList() wheres. ? , Linq . .ToList() , , , .

+3

, EF 7. :

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer).ThenInclude(c=>c.tbl_Address)
    .Where(...).ToList();

ThenInclude . .

Update

, , tbl_Customer null, Person Customer. , Customer, FK. , CustomerId int, Customer Address ( ), :

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer.tbl_Address)
    .Where(t => t.VendorID == person.VendorID &&
                t.FirstName == person.FirstName &&
                t.LastName == person.LastName &&
                t.tbl_CustomerId != 0 && // compare with default value of your FK property
                t.tbl_Customer.tbl_Address.State == address.State &&
                t.tbl_Customer.tbl_Address.City == address.City).ToList();
+2

Source: https://habr.com/ru/post/1618620/


All Articles