How to update only one field using Entity Framework?

前端 未结 16 1878
后悔当初
后悔当初 2020-11-22 09:09

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  我在风中等你
    2020-11-22 09:45

    Combining several suggestions I propose the following:

        async Task UpdateDbEntryAsync(T entity, params Expression>[] properties) where T : class
        {
            try
            {
                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;
            } 
        }
    

    called by

    UpdateDbEntryAsync(dbc, d => d.Property1);//, d => d.Property2, d => d.Property3, etc. etc.);
    

    Or by

    await UpdateDbEntryAsync(dbc, d => d.Property1);
    

    Or by

    bool b = UpdateDbEntryAsync(dbc, d => d.Property1).Result;
    

提交回复
热议问题