entity-frameworkentity-framework-6entity-framework-plus

Entity Framework Z Plus Batch Update


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
}

Solution

  • 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
    }