简体   繁体   中英

How to update all the records of a table in an entity framework?

I want to update all the records of the table and change the one column value but it is not working for me

What I tried:

public static void UpdateSellerAutoApprovalSettings(bool isSellerAutoApproved)
        {
            using (var context = GetDbContext())
            {
                context.SiteGroups
                    .AddOrUpdate(x => x.IsSellerAutoApproved, 
                    new SiteGroup { IsSellerAutoApproved = isSellerAutoApproved });
                context.SaveChanges();
            }
        }

只需使用ForEach扩展方法:

context.SiteGroups.ForEach(e => e.IsSellerAutoApproved = isSellerAutoApproved);

please check the below approach.

you can use where in between SiteGroups and ForEach if you need conditional Update

public static void UpdateSellerAutoApprovalSettings(bool isSellerAutoApproved)
{
    using (var context = GetDbContext())
    {
        context.SiteGroups
               .ForEach( x => x.IsSellerAutoApproved = isSellerAutoApproved )
        context.SaveChanges();
    }
}

You can use EntityFrmaework.Plus library like below

context.SiteGroups
         .Update(x => new SiteGroup { IsSellerAutoApproved = isSellerAutoApproved });

This will generate a SQL statement and you will not load all records into a application memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM