Reputation: 2629
How can i insert object twice in database with different value
when the object User
has Code > 10
then it insert 2 object but some how EF update the value of the first inserted object.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Code { get; set; }
}
and in my action i'm saving to databse
// Post Action
uow.Users.Add(user);
uow.Commit(); // save first time
if (user.Code > 10)
{
user.Name = "NAS";
uow.Users.Add(user);
uow.Commit(); //save second time
}
My object is
User = (Name = "Mike",Code=12)
Database result is
Result Database
id =1 Name="NAS" Code=12
id =2 Name="NAS" Code=12
Upvotes: 1
Views: 1995
Reputation: 9864
drneel gave a good explanation on why your code does not work as you intended.
Now maybe there is a workaround for what you want to achieve: inserting two distinct entities in DB from a single instance. Detach it from context, change what needs to be changed, re-add it.
If your uow
is inheriting from DbContext
, it would be:
var user = new User { Name = "Mike", Code = 12 };
uow.Users.Add(user);
uow.Commit(); // save first time
if (user.Code > 10)
{
uow.Entry(user).State = EntityState.Detached;
user.Id = 0;
user.Name = "NAS";
uow.Users.Add(user);
uow.Commit(); //save second time
}
I am not comfortable with the way we have to detach entities in EF. It may work better to instead dispose your uow
after first 'save' and use another one for second 'save'.
The main risk concerns navigation properties. Detaching does not ends tracking on collection of other entities which may hold a reference to your user instance. Re-adding it may screw EF navigation properties bookkeeping. (I would not fear that with NHibernate, such bookkeeping is not handled by NH. It remains the responsibility of the developer with NH.)
Upvotes: 1
Reputation: 2907
This is correct behavior; so why is this happening:
user
object.Your code should be:
var user = new User { Name = "Mike", Code = 12 };
uow.Users.Add(user);
uow.Commit(); // save first time
if (user.Code > 10)
{
var newUser = new User { Name = "NAS", Code = user.Code };
uow.Users.Add(newUser);
uow.Commit(); //save second time
}
Your results should then be:
Result Database
id = 1 Name = "Mike" Code = 12
id = 2 Name = "NAS" Code = 12
Upvotes: 4