user4229770
user4229770

Reputation:

filter a list with a table by multiple properties

I have a table in database which is called LineDocuments and contains three columns:

public int Id { get; set;}
public int DocumentId { get; set;}
public int LineId { get; set;}

And i have a method which wants to add new lineDocuments but do not want to insert the DocumentId and LineId combination in a database table.

For example if there is already a record in a database like this exist:

Id - 1, DocumentId - 1, LineId - 1. And there comes a list with a record also with DocumentId - 1 and LineId - 1 do not allow to insert this record since it has already that combination.

What is appropriate way to filter this list ?

I have only add method for now, it looks like this:

public void AttachLinesToDocs(List<LineDocuments> linesDocuments)
{
    foreach (var lineDocument in linesDocuments)
    {
        dbConnection.LineDocuments.Add(lineDocument);
    }

    dbConnection.SaveChanges();
}

Hope everything is clear, any help would be appreciated.

Upvotes: 0

Views: 408

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460298

Well, you could check it first:

public void AttachLinesToDocs(List<LineDocuments> linesDocuments)
{
    var insertValid = from doc in linesDocuments
                      where !dbConnection.LineDocuments
                        .Any(x => x.DocumentId == doc.DocumentId && x.LineId == doc.LineId)
                      select doc;
    foreach (LineDocuments lineDocument in insertValid)
    {
        dbConnection.LineDocuments.Add(lineDocument);
    }
    dbConnection.SaveChanges();
}

This uses one query to check all documents before it saves the valid documents.

Upvotes: 1

ajaysinghdav10d
ajaysinghdav10d

Reputation: 1957

This should help you:

public void AttachLinesToDocs(List<LineDocuments> linesDocuments)
{
  var qualifiedLineDocuments = linesDocuments.Where(inputld=> !dbConnection.LineDocuments.Any(ld=> ld.DocumentId== inputld.DocumentId && ld.LineId== inputld.LineId)).ToList();
      qualifiedLineDocuments.ForEach(qld=> 
      {
        dbConnection.LineDocuments.Add(qld);
      });
  }
}

Upvotes: 0

Related Questions