Reputation: 12852
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?
Upvotes: 0
Views: 139
Reputation: 54514
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.
Upvotes: 3
Reputation: 6294
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();
Upvotes: 2