Home > Back-end >  Is there a way to add data into a linking table of a many to many relationship in ASP.NET MVC?
Is there a way to add data into a linking table of a many to many relationship in ASP.NET MVC?

Time:03-30

I have two tables Documents and Groups. I have a linking table called DocumentsGroups which contains both the documents and group ID.

I want to insert data into DocumentsGroups. I am getting a list of IDs of documents and and one ID of group and iterating through the list as below:

// List<DocumentIds> obj;
// groupId = 1;

var group = this._database.Groups.Single(d => d.Id == groupId);

// Looping through all the documents 
foreach(var doc in obj.DocumentsId)
{
    var document = this._database.Documents.Single(d => d.Id == doc);
    group.Documents.Add(document);
}

I am first finding the group object with the group ID of the commented out code. Then I am looping through the document list and grabbing an object of each document and then use it to add to the linking table but I get an error on the last line

Object reference not set to an instance of an object

GroupDocuments is a model which contains the IDs of the documents i am trying to add into the database so am receiving it from a view. I am indeed getting a single document object as I am looping through and i dont know how this error is coming. Does anyone know a work around?

CodePudding user response:

you have to include documents before adding or create a list

var group = _database.Groups.Where(d => d.Id == groupId).Include(i=>i.Documents).FirstOrDefault();

if (group!=null)
{
   if (group.Documents==null) group.Documents=new List<Document>();

// and only now you can start adding
foreach(var doc in obj.DocumentsId)
{
    var document = _database.Documents.Where(d => d.Id == doc).Single();
 
    group.Documents.Add(document);
}
_database.SaveChanges();
}
  • Related