Question

I am trying to return a result set that includes rows where any of three strings has a string match. My domain models look like this:

public class Customers
{
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class BidNames
{
    public int BidNameID { get; set; }
    public int CustomerID { get; set; }
    public string BidName { get; set; }
}

There is a FK between BidName.CustomerID and Customers.CustomerID and it is a one-to-many relationship where there can be multiple BidNames for a single Customer. When searching my customer table I want to bring back all records where there is a string match in FirstName, LastName or any of the associated BidNames. For this example I'll use a BidName search string of "ba".

from c in Customers
where c.FirstName.Contains("ba") || c.LastName.Contains("ba") || c.BidNames.Any(b=>BidNames.BidName.Contains("ba"))
orderby c.LastName, c.FirstName
select new { CustomerID = c.CustomerID, FirstName = c.FirstName, LastName = c.LastName }

It all works until I add the final criteria in the Where clause. I understand that c.BidNames is a collection and I'm looking to see if Any of them have a BidName that contains "ba". Where I'm running into trouble is trying to specify the BidNames.BidName column to search for the string. The code I've written above fails with "BidNames does not contain a definition for 'BidName'"

How do I write the last part of the Where clause so I can search all the BidNames.BidName fields associated with the Customer record? I hope and assume I can use the same syntax to specify the BidName field in the orderby and select clauses as well.

Many thanks,

BK

FINAL ANSWER:

from c in Customers
where 
    c.FirstName.Contains("ba") || 
    c.LastName.Contains("ba") || 
    c.BidNames.Any(b=>b.BidName.Contains("ba"))
orderby 
    c.LastName, 
    c.FirstName
select new { 
    CustomerID = c.CustomerID, 
    FirstName = c.FirstName, 
    LastName = c.LastName,
    BidNames = c.BidNames.OrderBy(b=>b.BidName)
    }
Was it helpful?

Solution

Try changing your where clause to

Where c.FirstName.Contains("ba") || 
      c.LastName.Contains("ba") || 
      c.BidNames.Any(b=>b.BidName.Contains("ba"))

In your Any clause, b is an instance of the BidNames class, so you want to access properties of that rather than the BidNames property of the Customer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top