Answer the question
In order to leave comments, you need to log in
How to display a list of employees attached to animals?
I have 2 models - animals and employees. I want to link them together and bring out several employees who are tied to one animal and I don't know how to do it. Through models, controllers or views?
Animals
public class Animal
{
[Key]
public int AnimalId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public Eat Eats { get; set; }
public int StaffId { get; set; }
public virtual Staff Staff { get; set; }
}
public class Staff
{
[Key]
public int StaffId { get; set; }
public string SecondName { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
public int Exp { get; set; }
public int Pay{ get; set; }
public ICollection<Animal> Animals { get; set; }
}
Answer the question
In order to leave comments, you need to log in
1. You have "several employees who are tied to one animal" does not match your own code. Your animals only have 1 employee. You have a 1 to many relationship. For "several employees who are tied to one animal" you need "many-to-many".
2. "Through models, controllers or views?". Through everything. The controller sends a model to the View, which is rendered in the View.
3. Solution:
3.1 First make a many-to-many relationship:
public class Animal
{
[Key]
public int AnimalId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public Eat Eats { get; set; }
public virtual ICollection<Staff> { get; set; }
}
//Метод контроллера, который вызывается при переходе на страницу. (example: localhost/Home/ShowStaff/2959)
public async Task<IActionResult> ShowStaff(int animalId)
{
var result = await context.Animals.Include(x => x.Staff).FirstOrDefault(x => x.AnimalId == animalId); //Получаем всех сотрудников для животного
return View(result); //отдаем результат во view
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question