我有一种方法可以为我开发的API生成保存功能。如何正确保存到我的数据库?
以下3行未根据我在ASP.NET实体框架中调用SaveChanges将quantityPicked和productIdPicked保存到我的数据库。
namespace Services
{
public interface IUnitOfWork : IDisposable
{
Data.SupplyWizardsContext DBContext();
IGenericRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
void Dispose();
void Save();
}
}
public bool UpdateOrderPicks(int orderId, int orderItemId, int quantityPicked, int productIdPicked)
{
var orderItem = orderItemRepository.Get(oi => oi.OrderID == orderId && oi.OrderItemID == orderItemId).FirstOrDefault();
if (orderItem != null)
{
orderItem.PickedQuantity = quantityPicked;
orderItem.ProductPickedId = productIdPicked;
unitofwork.DBContext().SaveChanges();
return true;
}
return false;
}
public override int SaveChanges()
{
foreach (var history in this.ChangeTracker.Entries()
.Where(e => e.Entity is IModificationHistory && e.State == EntityState.Added
|| e.State == EntityState.Modified).Select(e => e.Entity as IModificationHistory))
{
if (history != null)
{
history.DateModified = DateTime.Now;
if (history.DateCreated == DateTime.MinValue)
history.DateCreated = DateTime.Now;
}
}
int result = base.SaveChanges();
return result;
}
public IGenericRepository<TEntity> GetRepository<TEntity>() where TEntity : class
{
if (repositories.Keys.Contains(typeof(TEntity)))
return repositories[typeof(TEntity)] as IGenericRepository<TEntity>;
var repo = new GenericRepository<TEntity>(context);
repositories.Add(typeof(TEntity), repo);
return repo;
}
如何使用第3行将quantityPicked / productIdPicked正确保存到数据库?
答案 0 :(得分:1)
我将走出困境,并认为orderItemRepository
实际上与您的unitofwork
无关。
但是,如果没有看到您的unitofWork
很难说,理想情况下,您的unitofwork
上会有一个属性用于存储库。
你似乎也是,通过你的单元工作暴露DbContext - 这可能有点危险,因为你现在不再控制对DBContext的访问。
例如,并非100%正常工作的代码,但您会明白这一点:
public class unitofWork(){
private YourDBContext_dbContext = new YourDBContext_dbContext();
public OrderItemRepository OrderItemRepository
{
get
{
return _orderItemRepository ?? (_orderItemRepository = new OrderItemRepository(_dbContext));
}
}
public void Save()
{
//your save logic save changes you want
_dbContext.SaveChanges();
}
}
因此,您可以在编码中执行以下操作:
var orderItem = unitofWork.OrderItemRepository.Get(oi => oi.OrderID == orderId && oi.OrderItemID == orderItemId).FirstOrDefault();
if (orderItem != null)
{
orderItem.PickedQuantity = quantityPicked;
orderItem.ProductPickedId = productIdPicked;
unitofwork.DBContext().SaveChanges();
return true;
}
return false;