Amila Dulanjana Amila Dulanjana - 1 month ago 7
ASP.NET (C#) Question

How to add multiple objects to a foreign table using Entity Framework

I am new to Entity Framework. I have two tables called

Polls
and
Candidates
which have a one-to-many relationship.

I want to add multiple candidates to a poll.

This is my code:

public bool InsertPolls(PollModel _polls)
{
polls = new Poll();
candidates = new candidate();

polls.Name = _polls.name;
polls.startDate = startDate;
polls.endDate = endDate;
polls.Type = _polls.pollType;

foreach (var candidatesID in _polls.candidateID)
{
candidates.Person_ID = candidatesID;
candidates.Poll = polls;
_dbContext.candidates.Add(candidates);
_dbContext.SaveChanges();
}
}


But this throws an exception


An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code Additional information: The property 'Person_ID' is part of the object's key information and cannot be modified.


Can anyone help me with this?
Thank You!

Answer

for remedy this problem put in first line in the for loop flowing code

candidates = new candidate();

also remove candidates = new candidate(); from top of code . the flowing code in for loop remove too

 candidates.Poll = polls;

because you have added in the top of code.

this is the final code

public bool InsertPolls(PollModel _polls)
{       
    polls = new Poll();

    polls.Name = _polls.name;
    polls.startDate = startDate;
    polls.endDate = endDate;
    polls.Type = _polls.pollType;
    _dbContext.Polls.Add(polls);
    _dbContext.SaveChanges();

    foreach (var candidatesID in _polls.candidateID)
    {
        candidates = new candidate();
        candidates.Person_ID = candidatesID;
        _dbContext.candidates.Add(candidates);
        _dbContext.SaveChanges();
    }
}
Comments