Boom Click
Boom Click

Reputation: 51

How to delete multiple data using entity framework and asp.net?

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?

Upvotes: 1

Views: 399

Answers (2)

Maciej
Maciej

Reputation: 1

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.

Upvotes: 0

JuanR
JuanR

Reputation: 7783

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();
}

Upvotes: 3

Related Questions