5

Is it possible to use Inner Join in the FromSql method of Entity Framework core?

I used, but I got this error:

SqlException: The column 'Id' was specified multiple times for 'c'.

This is my code:

return DbContext.Contacts
    .FromSql<Contact>("Select * From Contacts Inner Join Phones on Phones.ContactId = Contacts.Id Where Contacts.Id <= 2 And Phones.PhoneNumber='01234567890'")
    .Include(o => o.RegisteredByUser)
    .AsNoTracking()
    .ToListAsync();

1 Answer 1

3

Your Id column appears in both the tables, Phones and Contacts. Instead of putting *, you better choose the fields required in your query like following.

Please note, you need to specify which Id you want, If you want both, in that case you can use alias names like following.

Select Phones.Id as PhoneId, Contacts.Id as ContactsId, ....

Your final query should look like following query.

Select Contacts.Id, ... From Contacts Inner Join Phones on Phones.ContactId = Contacts.Id Where Contacts.Id <= 2 And Phones.PhoneNumber='01234567890

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.