1
嗯,我有一個奇怪的問題。我有訂單,訂單都有車,車中有車的物品收集,其中包括產品,它的數量:當我插入父實體存儲庫它插入子實體的重複
訂單:
public class Order : DatabaseEntity
{
public Order(Cart cart)
{
Cart = cart;
}
public int Id { get; set; }
[Required]
public Cart Cart { get; set; }
...
}
車:
public class Cart : DatabaseEntity
{
public ICollection<CartItem> Items { get; set; }
public void AddItem(Product product)
{
// Check is there such item, is Items null, update quantity
// if there is already such item bla bla
Items.Add(new CartItem(product));
}
...
}
車項目:
public class CartItem : DatabaseEntity
{
public CartItem(Product product)
{
Product = product;
Quantity = 1;
}
public Product Product { get; set; }
public int Quantity { get; private set; }
}
問題是當我創建新訂單並嘗試將其放置在數據庫中時,我得到重複的產品記錄SE。爲什麼會發生這種情況,我從來沒有遇到過這個問題。缺少什麼? OO:
[HttpPost]
public ActionResult MakeOrder(MakeOrderViewModel makeOrderModel)
{
...
var cart = Session["cart"] as Cart;
var order = new Order(cart);
orderRepository.PlaceOrder(order);
...
}
訂單倉庫:
public void PlaceOrder(Order order)
{
_repository.InsertOrUpdate(order);
}
和庫本身:
public class EFDatabaseRepository
{
...
public void InsertOrUpdate<TObject>(TObject entity) where TObject : DatabaseEntity
{
var entry = _database.Entry(entity);
if(entry.State == EntityState.Detached)
{
// New entity
_database.Set<TObject>().Add(entity);
}
else
{
// Existing entity
_database.Entry(entity).State = EntityState.Modified;
}
Save();
}
private void Save()
{
_database.SaveChanges();
}
}
DatabseEntity是id字段剛下課
public class DatabaseEntity
{
public int Id { get; set; }
}
我的數據庫上下文類:
public class DataBase : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<Cart> Carts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CartItem>().HasRequired(ci => ci.Product);
modelBuilder.Entity<Cart>().HasMany(c => c.Items);
base.OnModelCreating(modelBuilder);
}
}