Hi @Bipin,
The model design for one-to-many relationship should be:
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int WorkId { get; set; }
public Work Work { get; set; } = null!;
}
public class Work
{
[Key]
public int Id { get; set; }
public string? WorkName { get; set; }
public List<Person> Person { get; set; } = new List<Person>();
}
For how to save one or many Person to Work, a simple demo you could refer :
public async Task<IActionResult> Create(Work work)
{
if (!ModelState.IsValid)
{
return View();
}
var person1 = new Person()
{ Name = "aa" };
var person2 = new Person()
{ Name = "bb" };
Work.Person.Add(person1);
Work.Person.Add(person2);
_context.Work.Add(work);
await _context.SaveChangesAsync();
return View();
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Rena