1

Hi I'm now learning about entity framework and still a beginner. Now, I've been having a problem with deleting multiple data in my database. Here is a piece of my database:

Please click to see the image for database

For example i wanted to delete all data that has a brandId of 2. I tried using this code:

 int brandId = (from i in context.brands where i.name == name.Text select i.brandId).First();
var bay2 = (from g in context.logoes where brandId == g.brandId select g).FirstOrDefault();

        if (bay2 != null)
        {
            context.logoes.Remove(bay2);
            context.SaveChanges();
        }

But it only deletes one data, which is logoId 3. It did not delete logoId 4. What am i doing wrong in my query? How to delete all data that has brandId 2 using entity framework?

1
  • i believe you could remove multitple logo using RemoveRange.. Commented Jul 31, 2017 at 13:35

2 Answers 2

3

This line is pulling only one object:

var bay2 = (from g in context.logoes where brandId == g.brandId select g).FirstOrDefault();

Because of the FirstOrDefault.

Remove the FirstOrDefault. Then use RemoveRange:

var bay2 = (from g in context.logoes where brandId == g.brandId select g).FirstOrDefault();

if (bay2.Any())
{
    context.logoes.RemoveRange(bay2);
    context.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use .ToList() method instead of First(). Then Iterate over this for example list using foreach and delete these objects, or delete whole range.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.