To simplify my problem let's say I have the folowing database model:
// database model, the list of not supported postcodes
var postcodeExclusionArray = new List<PostcodeExclusion>() {
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "A11"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "A12"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "A12 4FR"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "AR"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "B11"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "B12"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "C11"
},
new PostcodeExclusion(){
CustomerId = 2,
Postocde = "C12"
},
// many more records...
};
It describes unsupported UK postcodes. It's only a concept of a data source as normally we use EF Core 3.1. Please bear in mind the format of each record can vary in gathering the whole area e.g. EH
or a particular property only e.g. AB25HZ
.
Now I want to check if the provided UK postcode is supported by my system.
My idea was to do it in the query using Where
statement only but I'm not sure if it's possible at all.
The idea for the algorithm is to get the combinations of the provided postcode in a way such as
providedpostCode = "A41666";
the combinations:
A
A4
A41
A416
A4166
A41666
Then build db query such as
bool isSupported = postcodeExclusionArray.Where(x => x.CustomerId == 2)
.Where(x=> x.Postocde == "A" ||
x.Postocde == "A" ||
x.Postocde == "A4" ||
x.Postocde == "A41" ||
x.Postocde == "A416" ||
x.Postocde == "A41666").First() == null;
Is there a way to achieve this using LINQ (not raw SQL) and if not what is the most optimal solution?
I tried to play with the foreach
loop but I didn't manage to find any solution.
If it's not possible then probably the easiest solution would be to generate the raw SQL query,
however, the minus of this approach would be that unit testing wouldn't be possible and this could only be tested by the integration test.
The other alternative would be to just query for all the postcodes from the db by customerId and do a simple iteration.
Any ideas?
Cheers