I have a piece of code that ensures that a customer's addresses are in sync with modifications made in the UI:
var customerAddresses = customer.CustomerAddresses.Select(x => x.Address);
// add address to customer if it does not already exist
foreach (var addressModel in model.Addresses)
{
// make sure an address matches all properties
Func<Address, bool> addressFilter = x => x.Id == addressModel.Id &&
x.Street.Equals(addressModel.Street, StringComparison.OrdinalIgnoreCase) &&
x.City.Equals(addressModel.City, StringComparison.OrdinalIgnoreCase) &&
x.Province.Equals(addressModel.Province, StringComparison.OrdinalIgnoreCase) &&
x.PostalCode.Equals(addressModel.PostalCode, StringComparison.OrdinalIgnoreCase);
// check if customer already has this address
if (!customerAddresses.Any(addressFilter))
{
// check if address already exists in database
var address = this.DbContext.Addresses.SingleOrDefault(addressFilter);
// add address if it does not exist
if (address == null)
{
address = this.DbContext.Addresses.Add(new Address
{
Street = addressModel.Street,
City = addressModel.City,
Province = addressModel.Province,
PostalCode = addressModel.PostalCode
});
}
}
this.DbContext.CustomerAddresses.Add(new InsuredAddress
{
Customer = customer,
Address = address,
IsPreferred = addressModel.IsPreferred
});
}
I am however concerned that the Func<Address, bool> addressFilter is created every time inside the loop. Is there a way to create filter in such a way that it accepts parameters and does not need to be recreated each time?