Tutorial :Update ONLY some fields of attached Entity



Question:

I'm using .NET 3.5 SP1. I have entity 'AppUser':

public class AppUser : System.Data.Objects.DataClasses.EntityObject{      public int Uid {get; set;}      public string UserName {get; set;}      public string Password {get; set;}      public DateTime LastLogin {get; set;}      public string Name {get; set;}      public string Address {get; set;}   public string Comment {get; set;}    ...........     }   

To update ALL fields of an attached enitity:

   public void Update(AppUser updateUser) {      AppUser user = ctx.AppUserSet.Where(u => u.UserId == userId).FirstOrDefault();      //This will update ALL fields      ctx.ApplyPropertyChanges(user.EntityKey.EntitySetName, updateUser);      ctx.SaveChanges();         }    

I want to update all fields except Password and LastLogin. I can update individual fields, but will be cumbersome for entities with large number of fields.

Please tell, what is the best way to achive this?

Thank You.


Solution:1

Change the setters for those two properties to private in the EDMX/model.


Solution:2

I don't think that you can do this directly with EF without extra programming effort.

There are three possibilities:

  • Update through a view
  • Update using a stored procedure
  • Change your data model, such that the password and lastlogin are in a seperate table with a one to one relationship.

All of these require extra programming effort.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »