V
V
Vladislav2017-02-24 17:44:34
.NET
Vladislav, 2017-02-24 17:44:34

.net web api & Entity Framework 6 link multiple tables?

Hello. Such a problem: I am making a REST API in .net web api & Entity Framework 6, I have made basic conclusions from 1 table, but I can’t understand how to properly arrange these tables, not by the ID key field.
1 model/table - users
A user can have sub-users, i.e. each user has a parent_id parameter in addition to his id.
2 model/table - cars
There is a user_id field, ie a car can be assigned to only 1 user.
The task is this: Knowing your user_id, you need to find all your sub-users and their cars.
Ie something like: Take from the table of users, users whose parent_id == my id and add cars from the auto table, if id (of the user) == user_id (from the auto table).
That is, the output should be an array of user objects, inside which is an array of car objects. (Because several cars can be tied to 1 person).
I understand that you need to create another model. I created one like this:

public class UserCars
    {
        public int Id { get; set; }
        [Required]
        public int ParentId { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string FirstName { get; set; }
        public string SecondName { get; set; }
        public string Surname { get; set; }

        public int UserId { get; set; }
        public Car Car { get; set; }
    }

And accordingly the controller, I got this:
// GET: api/CarChildrens/5
        [ResponseType(typeof(UserCars))]
        public async Task<IHttpActionResult> GetUserCars(int id)
        {
            var usersCar = await db.UserCars.Where(x => x.ParentId == id).Include( x => x.Car.UserId == x.UserId).ToListAsync();
            if (usersCar == null)
            {
                return NotFound();
            }

            return Ok(usersCar);
        }

But an empty array comes. How can I debug a query to the database and what is the error? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrDywar Pichugin, 2017-02-24
@Dywar

1) Read the full https://metanit.com/sharp/entityframework/
2) Use the Fluent API.
3) Use navigation properties.
4) To view the SQL Query generated by EF 6, you need to specify the setting for this, and the queries will be written to the output window. https://msdn.microsoft.com/en-us/library/dn469464(...
Next, if possible, you need to read everything on the same metanit information about MVC 5, API 2.0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question