0

I want to update few columns on my table.

    public void LogOutUser(int systemUserId)
    {
        DatabaseContext context = new DatabaseContext ();
        var user = new SystemUser()
        {
            SystemUserId = systemUserId,
            IsLocked = true,
            IsLoggedIn = false
        };

        context.SystemUsers.Attach(user);
        context.Entry(user).Property(x => x.IsLocked ).IsModified = true;
        /context.Entry(user).Property(x => x.IsLoggedIn ).IsModified = true;

        context.SaveChanges();
    }

It's giving me an error "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.". I am aware that this error happens because I have some Properties in my "SystemUsers" class that are required, like Email, FullName, etc. I could have easily done it when I use connected scenario..

var user = context.SystemUsers.Find(systemUserId);
user.IsLocked = true;
user.IsLoggedIn = false;
context.SaveChanges();

But I don't want to use this way as I believe it's a waste of resources as I have to fetch the whole row first then update it. Now, my question is, what is the best way to update EF using disconnected scenario given that I only have "systemUserId" as a way of telling the EF that this data is existing in my database.

  • you can use stored procedure instead! so you pass the userId to the procedure parameter, and the SQL engine will take care of the rest ! – iSR5 Aug 10 '20 at 06:33
  • 1
    @iSR5 it will defeat the purpose of using EF. – Jeremy Cruz Aug 10 '20 at 06:48
  • `it will defeat the purpose of using EF` ? no it's not, EF is an ORM and not an SQL engine substitute. So, taking advantage of both parties would give you the best possible experience (performance, handling ..etc.). – iSR5 Aug 10 '20 at 07:00
  • Updating 2 columns using stored procedure when you have EF installed makes no sense. – Jeremy Cruz Aug 10 '20 at 07:25
  • You could use `context.SystemUsers.SqlQuery` that's raw sql – iSR5 Aug 10 '20 at 07:30
  • The answer in this link allows you to only validate what you need to rather than disabling all EF validation. https://stackoverflow.com/a/29689644/7030091 – hobomaan Aug 10 '20 at 18:39

1 Answers1

0

I found the solution for this problem. I just added this line code before SaveChanges();

context.Configuration.ValidateOnSaveEnabled = false;

ValidateOnSaveEnabled is set true by default, and making this false would not require EF to validate your entities before saving.