Entity framework creates new record when SaveChanges is called

I have two objects:

public class Order:Entity
{
   public virtual User User { get; set; }
   ...
}

public class User:Entity
{
   public virtual ICollection<Order> Orders { get; set; }
   ...
}

      

Next, I create the order:

var order = _orderService.CreateTransientOrder(orderNumbers, PcpSession.CurrentUser);
PcpSession.Order = order;

      

it is CreateTransientOrder

. It only creates Order

, but does not store in the database:

public Order CreateTransientOrder(string orderNumbers, User currentUser)
{
   ...fill fields
   order.User = currentUser;
   return order;
}

      

Now everything is all right. Then I save the order to the database:

_orderService.CreateOrder(PcpSession.Order);

      

This CreateOrder

:

public void CreateOrder(Order order)
{
    order.OrderDate = DateTime.Now;
    _repository.Save(order);
    _repository.SaveChanges();
}

      

This is my Save

repository method :

public void Save<T>(T entity) where T : class, IEntity
{
    _context.Set<T>().Add(entity);
}

      

When called SaveChanges

, a new user is created in the database with a new ID and the order has a new User_Id. In the debugger, in the method, the CreateOrder

identifier is the current user. Where is the problem?
Thank you.

+3


source to share


2 answers


The user is probably not being tracked by the context. When you add an order to the context, it also adds related objects and then saves the changes creates a new user (or tries). Attach()

user in context before calling _context.Set<T>().Add(entity);

.



+2


source


I guess the problem is not related to the code you provided. It seems to have something to do with where you are initializing PcpSession.CurrentUser

.



It seems that the object is PcpSession.CurrentUser

not context bound. Either bring that object into context before making Order

associated calls to you or attaching it.

+1


source







All Articles