Entity Framework Z Plus Batch Update


Question

I am using Entity Framework Z Plus Batch Update method. I am unable to proceed due to below issue. Actually Update method works good when i give static values like tagName="amir1". But I need to get the Tagdescription from a web service or from another collection based on the tagId, Update method is not accepting a extension method or any other method to accomplish my requirement.Its saying

"LINQ to Entities does not recognize the method 'System.String GetTagDescription(Int32)' method, and this method cannot be translated into a store expression.".

Hope my requirement is clear now. Please guide me if there is any other approach for my requirement.

Here is my code:

using (var context = new TrialsDBEntities())
{
     context.tblTags.Where(x => (tagIdCollection.Contains(x.tagId))).
                Update(m => new tblTag { tagDescription = m.tagId.GetTagDescription(), tagName = "amir1" });
}

public static string GetTagDescription(this int i)
{
     return "test" + i;

     ///Replace above line with call to database or web service call 
     getting some text by giving i as input
}

Accepted Answer

Write your code as follows:

using (var context = new TrialsDBEntities())
{
   var tagsToBeUpdated =  context.tblTags.Where(x => (tagIdCollection.Contains(x.tagId))).AsNoTracking().ToList();

   //Only use this code block if your tagsToBeUpdated list is too large
   Parallel.ForEach(tagsToBeUpdated, tagToBeUpdated =>
   {
      var tagDescription = GetTagDescription(tagToBeUpdated.tagId);
      tagToBeUpdated.tagDescription = tagDescription;
      context.Entry(tagToBeUpdated).State = EntityState.Modified;
   });

   //Only use this code block if your tagsToBeUpdated list is not too large
   foreach(var tagToBeUpdated in tagsToBeUpdated)
   {
      var tagDescription = GetTagDescription(tagToBeUpdated.tagId);
      tagToBeUpdated.tagDescription = tagDescription;
      context.Entry(tagToBeUpdated).State = EntityState.Modified;
   }

   context.SaveChanges();         
}

public static string GetTagDescription(int i)
{
     return "test" + i;

     ///Replace above line with call to database or web service call 
     //getting some text by giving i as input
}

Expert Answer

Disclaimer: I'm the owner of the project Entity Framework Plus

Unfortunately, that's not possible to use BatchUpdate with a value that changes from a row to another.

Disclaimer: I'm the owner of the project Entity Framework Extensions

In this situation, we normally recommend using our paid library that's build for this kind of situation and offer high-performance saving operation.

Example

// Easiest way
context.BulkSaveChanges();

// Fastest way
context.BulkUpdate(tags);




Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why