Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LINQ C# – API CONTROLLER – Evaluate query

I have a table called "Cowork" and another called "Commune". In a controller I receive a parameter called NameCommune, given that value I need to find the ID that matches the received parameter, the result of the above I need to evaluate if that ID exists in the "COWORK" table. (THE TWO TABLES ARE RELATED) I’m new to using LINQ, any ideas for this? I have tried the following, but it returns an empty [ ]

public  IActionResult GetNearbyPlaces(string nameComuna)
        {
            IQueryable<Commune> queryCommune = _context.Commune;
            IQueryable<Cowork> queryCowork = _context.Cowork;

            var codeCommune = (from code in queryCommune where code.name == nameComuna select code.code);
            
            var coworkList = (from c in _context.Cowork where c.commune_code == codeCommune.ToString() select c).ToList();

            return Ok(coworkList); // This returns an empty [ ]
        }

In my common table the ID or my primary key is represented by the name code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You probably want something like this:

public IActionResult GetNearbyPlaces(string nameComuna)
{
    IQueryable<Commune> queryCommune = _context.Commune;
    IQueryable<Cowork> queryCowork = _context.Cowork;

    var query =
        from code in queryCommune
        where code.name == nameComuna
        join c in _context.Cowork on code.code equals c.commune_code
        select c;

    return Ok(query.ToList());
}

Or possibly:

public IActionResult GetNearbyPlaces(string nameComuna)
{
    IQueryable<Commune> queryCommune = _context.Commune;
    IQueryable<Cowork> queryCowork = _context.Cowork;

    var query =
        from c in _context.Cowork
        join code in queryCommune.Where(x => x.name == nameComuna)
            on c.commune_code equals code.code into codes
        where codes.Any()
        select c;
        
    return Ok(query.ToList());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading