How to update one field of specific records using Entity Framework?

前端 未结 6 1386
别跟我提以往
别跟我提以往 2021-01-31 11:10

I want update family of a person who his name is pejman. This is my object Class:

public class Person
{
    public int Id { get; set; }
    public string FirstNa         


        
6条回答
  •  一整个雨季
    2021-01-31 11:45

    EDIT: assume that i don't know person's Id, and i just know person's name, is there any way to update person's family?

    I'm assuming that the FirstName field of Person class contains the person's name, and updating the person's family means updating the LastName field.

    The first step is to get all Person records with FirstName equals the person's name, let's say it's "pejman" so the code would be as below.

    var personsToUpdate = newContext.Persons.Where(o => o.FirstName == "pejman");
    

    The next step is enumerate personsToUpdate and set the LastName property to the family name you want, then call .SaveChanges() method of the DbContext to submit the changes to the database. Let's say you want to update the person's family name to "MyFamilyName", the code would be as below

    foreach (Person p in personsToUpdate)
    {
        p.LastName = "MyFamilyName";
    }
    
    newContext.SaveChanges();
    

    The following is the modified code of your Update method with the name and family parameter.

    public static void Update(string name, string family)
    {
        using (var newContext = new MyDbContext())
        {
            // get all Persons with FirstName equals name
            var personsToUpdate = newContext.Persons.Where(o => o.FirstName == name);
    
            // update LastName for all Persons in personsToUpdate
            foreach (Person p in personsToUpdate)
            {
                p.LastName = family;
            }
    
            newContext.SaveChanges();
        }
    }
    

提交回复
热议问题