Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework creates new record when SaveChanges is called

I have two entities:

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

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

Next, I create order:

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

this is CreateTransientOrder. It's only create Order, but not save into database:

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

Now it's all ok. Next, I save order to the database:

_orderService.CreateOrder(PcpSession.Order);

This is CreateOrder:

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

This is my Save method of repository:

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

When the SaveChanges is called in the database creates new user with new ID and order have new User_Id. In the debugger in the CreateOrder method, Id is equal current user. Where is a problem?
Thanks.

like image 583
user1260827 Avatar asked Aug 24 '26 12:08

user1260827


2 Answers

User is probably not being tracked by the context. When you add order to the context it also adds the related entities and then on save changes creates a new user (or attempts to). Attach() the user to the context before you call _context.Set<T>().Add(entity);.

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

It seems PcpSession.CurrentUser object is not attached to the context. Either fetch this entity to the context before making you Order related calls or attach it.

like image 41
daryal Avatar answered Aug 26 '26 01:08

daryal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!