E
E
embiid2022-04-10 19:27:01
C++ / C#
embiid, 2022-04-10 19:27:01

How to check for two entities?

There are two entities => City and AlternativeCity.
Now the code only works for checking in the City entity

var city = await ctx.City.SingleOrDefaultAsync(x => x.CountryId == country.Id)


How to make a condition if there is no such in City, then look in AlternativeCity? And if both there and there is not, then an error?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
oleg_ods, 2022-04-11
@oleg_ods

Without seeing the entities themselves, it is difficult to advise something. But their fields are identical, you can try to put them in the same table and add a boolean IsAlternative field. Then query all cities and sort them by the IsAlternative field and take the first one. Thus, if there is a main city, you will get it; if there is no main city, you will get an alternative one; if null, you handle an error.
If the entities differ in structure, read about ef core inheritance, maybe this is what you need.

G
Griboks, 2022-04-11
@Griboks

Well, if you want to get rid of lines of code, then you can collapse them into one using the second argument (defaultValue), for example (I can mess up with async/await):

ICity city = await ctx.City.SingleOrDefaultAsync(x => x.CountryId == country.Id, await ctx.AlternativeCity.SingleOrDefaultAsync(x => x.CountryId == country.Id));

If entities have a common parent interface (should in theory), then it is desirable to use it.
Also, there is a possibility that this version will be heavier due to the calculation of the default value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question