curd operations for save public List<int> PersonIds { get; set; }

Bipin 0 Reputation points
2024-01-03T04:55:05.8033333+00:00

public class Person

{

[Key]

public int Id { get; set; }

public string Name { get; set; }

}

public class Work

{

[Key]

public int Id { get; set; }

public string WorkName { get; set; }

// Use a list of person IDs

public List<int> PersonIds { get; set; }

}

How to save one or more person to Work in C# mvc core 8

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,816 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,597 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2024-01-03T06:38:19.6466667+00:00

    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


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.