Reputation: 3435
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
Upvotes: 0
Views: 2177
Reputation: 51514
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
Upvotes: 2