简体   繁体   中英

Updating every item in a table with Linq / C#

I'm trying to replace all urls containing http: with https: in the Seed() method of my EF Code-first configuration. I have the following:

var context = new DbContext(); // contains public DbSet<Doc> Docs { get; set; }
var docs = context.Docs.ToList();  // dbcontext

foreach (var doc in docs)
{
    if (doc.ImageContent != null && doc.ImageContent.Contains("https:"))
        doc.ImageContent = doc.ImageContent.Replace("https:", "http:");
}
context.saveChanges

But whenever I run this (from my seed method in my database migration - so I can't debug as far as I know) - I get the following error:

System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. 

This error even occurs if I comment out SaveChanges. The field is just a non-required string so I don't think validation is failing due to incorrect data type... what else could it be?

I think you should change your code to this

foreach (var doc in context.Docs)

Since var docs = context.Docs.ToList(); will pull all objects in memory and context is not able to track any change.

You should be able to perform an update on any records that match a certain criteria. Instead of pulling the whole list narrow your results sets.

var context = new DbContext(); // contains public DbSet<Doc> Docs { get; set; }

foreach (var doc in context.Docs.Where(d => d.ImageContent.StartsWith("https:")))
{
    doc.ImageContent = doc.ImageContent.Replace("https:", "http:");
}

context.SaveChanges();

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