skip to Main Content

I am rewriting the ASP.NET Identity user system with Dapper instead of Entity Framework and encountered an issue while creating new user accounts.

We have a user object passed to us by identity that is inserted to a database, however that user object does not yet have the correct Id because Identity can’t know what auto-increment the database is up to yet.

So the SQL procedure that inserts the user object also returns all the data of the user that was just inserted, I’ll call this returned object retUser.

In C#, if I set the user object in the following way:

user.Id = retUser.Id;

then the Id is changed correctly and the user of the website can proceed as normal.
If I instead set the entire user model in the following way:

user = retUser;

Then C# instead "assigns by value" I assume, and does not actually change the global version of the user object.

Is there a single line assignment in C# that allows me to set the entire user object by reference? Or am I misunderstanding why this is occurring?

2

Answers


  1. Then C# instead "assigns by value" I assume, and does not actually change the global version of the user object.

    Assuming user is a class, this would be a reference assignment. I.e. user previously refereed to object A, but now refers to B. Other references might still refer to A, and A remains unchanged. Changing your reference is not the same as updating all the properties of a shared object. There is no built in function for this, but you could write one yourself

    public class User{
        public long Id {get; private set;}
        ...
        public void CopyPropertiesFromObject(User other){
            Id = other.Id;
        }
    }
    

    You could also add another level of indirection:

    public class Ref<T>{
        public T Value {get;set;}
    }
    

    That would allow you to change the the reference in a shared object. But it can make the code a bit more difficult to read and understand.

    If the problem is limited to the Id, I would just make sure to update the Id after each call. Or just try to reduce sharing of objects, so you can ensure all references actually are updated after the object has been saved.

    Login or Signup to reply.
  2. As far as I know dapper does not track the state of objects like EF so it should be perfectly fine to re-assign user with retUser unless you have something else that is tracking the state of user and will not pick up the re-assignment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search