jasonmit
jasonmit

Reputation: 1278

EF defer setting property until insert

public class User {
    int Id { set; get; } // autogenerated on insert
    public string Username { set; get; }
}

Then some where in my code I have the follow:

var user = new User();
user.Username = string.Format("user{0}", user.Id);
dbContext.User.Add(user);
dbContext.SaveChanges();
Debug.WriteLine(user.Username); // outputs "User0" when the Id is ..not 0

Upvotes: 1

Views: 62

Answers (2)

DavidAndroidDev
DavidAndroidDev

Reputation: 2414

The only way this is going to work for you is if you have your User first with an empty Username property, .SaveChanges(), and then user.Username = string.Format(...), then save again. Even if you were to write this through straight SQL, you don't know the ID of the row until the db commits the change.

What you're asking for isn't possible EDIT without multiple saves.

Upvotes: 0

Mark Oreta
Mark Oreta

Reputation: 10416

You're inserting a newly created user instead of inserting the one you created:

Change :

var user = new User();
user.Username = string.Format("user{0}", user.Id);
dbContext.User.Add(new User());

to:

var user = new User();
user.Username = string.Format("user{0}", user.Id);
dbContext.User.Add(user);

Upvotes: 1

Related Questions