简体   繁体   中英

using linq Query how can i update multipul Records

Here im getting Multipul values as 1,2,3 for ENQUIRY_CODE

public void HRUpdateStatus(string ENQUIRY_CODE, int uid)
{
    var x = (from e in db.EMS_ENQUIRYREGISTRATION_MASTER
             where e.ENQUIRY_CODE == ENQUIRY_CODE
             select e).ToList();

    foreach (var abc in x)
    {
        abc.HRowner = uid;
        db.SaveChanges();
    }
    ...
}

Please help me where im doing mistake

A LINQ statement will never change the source sequence .
LINQ is not meant to do that.

The proper solution depends on which kind of DbContext you are using. If you use entity framework you'll have to fetch the items before you can update one or more of the properties.

In your case, you want to change one property of all fetched values to the same new value. Consider creating an extension function for your DbContext. See extenstion methods demystified

The following takes an IQueryable sequence of some source class (TSource), and an action that should be performed on each source element.

public void ForEach<TSource>(this IQueryable<TSource> source,
    Action<TSource> action)
{
     var fetchedItems = source.ToList();
     foreach (var fetchedItem in fetchedItems)
     {
         action(fetchedItem);
     }
}

Usage:

using (var dbContext = new MyDbContext())
{
     db.EMS_ENQUIRYREGISTRATION_MASTER
       .Where (registrationMaster => registrationMaster.ENQUIRY_CODE == ENQUIRY_CODE)
       .ForEach(registrationMaster => registrationMaster.HRowner = uid);
     db.SaveChanges();
}

I chose to return void instead of IEnumerable<TSource> to indicate to users of the function that the queried data is materialized and might have been changed. After all the following might have been confusing:

IQueryable<Student> students = ...
var updatedStudents = students.ForEach(student => student.Grades.Add(new Grade(...))
    .Take(2)
    .ToList();

You want to communicate that all students are updated, not just the 2. Consider returning an IReadonlyList<TSource> or similar, so you don't have to materialize the data again.

I think this is what you mean:

var codes = ENQUIRY_CODE.Split(',').ToList();

var x= db.EMS_ENQUIRYREGISTRATION_MASTER.Where(s => codes.Contains(s.ENQUIRY_CODE)).ToList();

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