[英]How to update an entity using Entity Framework from Business Layer?
I my web application structured with 3 layers, controller, business logic and repository. 我的Web应用程序由3层结构构成:控制器,业务逻辑和存储库。
From the BL layer I am updating an entity with the following code. 从BL层,我使用以下代码更新实体。 As you can see I am updating property by property.
如您所见,我正在按属性更新属性。
I would like to know if there is a better way to do it, removing this manual mapping. 我想知道是否有更好的方法可以删除此手动映射。
---------------------- CONTROLLER ----------------------控制器
public IHttpActionResult Put(int id, DeviceDTO dto)
{
GaDevice device = Mapper.Map<GaDevice>(dto);
deviceBLL.Update(id, device);
return Ok();
}
---------------------- BL ---------------------- BL
public void Update(int id, GaDevice entity)
{
bool hasValidId = GetById(id) != null ? true : false;
if (hasValidId == true)
{
GaDevice device = deviceRepo.GetById(id);
device.CanNotifyPc = entity.CanNotifyPc; // NOT SURE HERE
device.CanNotifyPrinter = entity.CanNotifyPrinter;
device.LocationId = entity.LocationId;
device.Name = entity.Name;
device.Note = entity.Note;
device.OperativeFromTime = entity.OperativeFromTime;
device.OperativeToTime = entity.OperativeToTime;
deviceRepo.Update(device );
deviceRepo.Save();
}
---------------- Repository ----------------储存库
public void Update(GaDevice entity)
{
context.Entry(entity).State = EntityState.Modified;
}
What about saving the changes made to the context
in the Update()
? 如何将对
context
所做的更改保存在Update()
呢? Otherwise, what does your code in the Save()
do? 否则,您在
Save()
中的代码做什么?
public void Update(GaDevice entity)
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.