How to update only one field using Entity Framework?

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

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  悲哀的现实
    2020-11-22 09:49

    i'm using this:

    entity:

    public class Thing 
    {
        [Key]
        public int Id { get; set; }
        public string Info { get; set; }
        public string OtherStuff { get; set; }
    }
    

    dbcontext:

    public class MyDataContext : DbContext
    {
        public DbSet Things { get; set; }
    }
    

    accessor code:

    MyDataContext ctx = new MyDataContext();
    
    // FIRST create a blank object
    Thing thing = ctx.Things.Create();
    
    // SECOND set the ID
    thing.Id = id;
    
    // THIRD attach the thing (id is not marked as modified)
    db.Things.Attach(thing); 
    
    // FOURTH set the fields you want updated.
    thing.OtherStuff = "only want this field updated.";
    
    // FIFTH save that thing
    db.SaveChanges();
    

提交回复
热议问题