I have two tables in SQL server for customers and their addresses.
CREATE TABLE Customers
(
ID INT NOT NULL IDENTITY(1,1),
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(50) NOT NULL,
DateOfBirth DATETIME2 NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ([ID] ASC)
)
CREATE TABLE CustomerAddresses
(
ID INT NOT NULL IDENTITY(1,1),
CustomerID INT NOT NULL CONSTRAINT [FK_CustomerAddresses_Customers] FOREIGN KEY([CustomerID]) REFERENCES [dbo].[Customers] ([ID]),
Street VARCHAR(100) NOT NULL,
City VARCHAR(50) NOT NULL,
Country VARCHAR(50) NOT NULL,
CONSTRAINT [PK_CustomerAddresses] PRIMARY KEY CLUSTERED ([ID] ASC)
)
I have generated a EFdatamodel and connecting to it using DataContext. I am trying to get all customers for a particular country. My code is as follows.
static List<Customer> GetByCountry(string country)
{
MyDbContext MyContext = new MyDbContext ();
return MyContext.Customers.Where(x => x.CustomerAddresses.Where( y => y.Country == country)).ToList();
}
But I am getting following compilation errors.
Cannot implicitly convert type
‘System.Collections.Generic.IEnumerable’ to
‘bool’ Cannot convert lambda expression to delegate type
‘System.Func’ because some of the return
types in the block are not implicitly convertible to the delegate
return type
What am I doing wrong here?
Your code must be
Because you want to return all Customers that have any address with the specified country. Where() expects a function that returns whether the condition is true, and returns an enumeration of all elements which hold this condition true. In your outer Where() your supply an argument that is of type IEnumerable (which is the return value of your inner where), and that is wrong.