Maro
Maro

Reputation: 2629

Inserting object twice to EF 6

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

Answers (2)

Frédéric
Frédéric

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

drneel
drneel

Reputation: 2907

This is correct behavior; so why is this happening:

  • When you save the first time, it creates a new entry in the database using your originally created user object.
  • When you save the second time, it takes the original object, which for lack of a better term, has a database reference and updates the name of the object AND it also adds that same object to the collection again; this is why you are seeing the same information in the database.

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

Related Questions