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

前端 未结 6 1382
别跟我提以往
别跟我提以往 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:29

    assuming you have the instance of Person that the db can find (as mentioned by Paweł Bejger):

    public class Person
        {
            /// 
            /// USAGE: await UpdateDbEntryAsync(myPerson, d => d.FirstName, d => d.LastName);
            /// 
            async Task UpdateDbEntryAsync(T entity, params Expression>[] properties) where T : class
            {
                try
                {
                    var db = new RtTradeData.Models.ApplicationDbContext();
                    var entry = db.Entry(entity);
                    db.Set().Attach(entity);
                    foreach (var property in properties)
                        entry.Property(property).IsModified = true;
                    await db.SaveChangesAsync();
                    return true;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("UpdateDbEntryAsync exception: " + ex.Message);
                    return false;
                }
            }
    
            /// 
            /// The idea is that SomeFunction already has the instance of myPerson, that it wants to update.
            /// 
            public void SomeFunction()
            {
                myPerson.FirstName = "Another Name"; myPerson.LastName = "NewLastName";
                UpdateDbEntryAsync(myPerson, d => d.FirstName, d => d.LastName);
            }
            /// 
            /// Or directly requesting the person instance to update its own First and Last name...
            /// 
            public void Update(string firstName, string lastName)
            {
                FirstName = "Another Name"; LastName = "NewLastName";
                UpdateDbEntryAsync(this, d => d.FirstName, d => d.LastName);
            }
    
            Person myPerson = new Person { PersonId = 5, FirstName = "Name", LastName = "Family" };
            public int PersonId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    

    see as well update a single field in Entity Framework and Entity Framework update single

提交回复
热议问题