0

We have the following AddUser method which adds a new record to the database using EF:

    public User AddUser(User user)
    {
        using (var context = DataObjectFactory.CreateContext())
        {
            var userEntity = Mapper.Map(user);

            context.AddObject("UserEntities", userEntity);

            context.SaveChanges();

            return Mapper.Map(userEntity);
        }
    }

Our User type is like this:

public class User
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Customer Customer { get; set; }     
}

We have a Customer table and a User table and in User table we have customerid as a foreign key.

In the USER table we have Firstname, Lastname and CustomerId fields, we get the firstname, lastname and customerid (dropdown list of customers) details from the user, create the Customer object with customerid we get from the user and pass all of these to the AddUser method, but what happens is that the User gets inserted into the database and also a new Customer is inserted into the Customer's table (with a new customerid), is there any way of stopping this?

Thanks

1 Answer 1

2

You need to set the EntityState of the Customer to Unchanged.

Something like

 context.Entry<Customer>(customer).State = EntityState.Unchanged; 

or

 context.ObjectStateManager.ChangeObjectState(userEntity.Customer, EntityState.Unchanged); 

(depending on what kind of context you are using)

See http://msdn.microsoft.com/en-us/data/jj592676.aspx

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.