0

I'm in C# and using Entity Framework with a database-first approach, and I would like to do a query similar to this query but in an asynchronous way:

[Route("api/Tests/get/by/flight/{id}")]
[ResponseType(typeof(Test))]
public IHttpActionResult getByFlightTodayId(int id)
{
    var testList = db.Tests.SqlQuery("Select * from Tests where Tests.AircraftId=@id", new SqlParameter("@id", id)).ToList<Test>();
    return Ok(testList);
}

I have an example but it returns only one result - not an array.

[Route("api/Tests/get/by/flight/{id}")]
[ResponseType(typeof(Test))]
public async Task<IHttpActionResult> getByFlightId(int id)
{
    Test test = await db.Tests.FirstAsync(r => r.AircraftId == id);

    if (test == null)
    {
        return NotFound();
    }

    return Ok(test);
}

Also, I want to do an inner join query but I don't know how to do this.

Can someone help me?

Thanks

3
  • Do you have foreign key references between tables means, you can use db.Tests.Include(x=>x.TableName) Commented Dec 23, 2019 at 12:52
  • It's not very clear what you're trying to achieve, can you add an example of what result are you expecting? Commented Dec 23, 2019 at 13:03
  • Tests.aircraftId is a foreign key and I want all the tests an aircraft passed Commented Dec 23, 2019 at 13:07

1 Answer 1

3

Use like below:

var test = await db.Tests.Where(r => r.AircraftId == id).ToListAsync();

For Inner join, there will be foreign key relationship between 2 tables. Then you can use below query:

var test = await db.Aircraft.Include(x=>x.Tests).ToListAsync();

You can apply .Where condition, if you want to filter records in that.

Sign up to request clarification or add additional context in comments.

3 Comments

I do this but an error occured : "Cannot implicitly convert type : 'system.Collections.Generic.List<toulouseTech2;Models.Test>' to 'toulouseTech2.Models.Test'
Try now, change Test to var or List<Test>
it's working !!! Thanks a lot. Can you tell me how can I do this for an inner join query like : Select * From Aircraft Inner Join Test On aircraft.Id = test.AircraftId

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.