簡體   English   中英

在C#/ LINQ中將實體模型與DTO模型進行比較的最有效方法

[英]Most efficient way to compare an Entity Model to a DTO Model in C#/LINQ

只有當一個或多個屬性與當前EF對象不同時,我才會傳回一個DTO對象,其中包含我想在數據庫中更新的十幾個屬性。 使用C#和Lambda語法LINQ實現此目的的最簡單方法是什么?

試試這個例子。

    [HttpPost]
    [Route("Client/UpdateClient")]
    [Authorize]
    public ActionResult UpdateClient(ClientDTO client)
    {
        var user = GetLoggerUser(BOAccount);            
        client.LastModifiedBy = user.EmailAddress;
        client.LastModifiiedOn = DateTime.UtcNow;            
        var resultclient = BOClient.UpdateClient(client, user);
        return Json(resultclient);
    }
    // BOClient.UpdateClient
    public ClientDTO UpdateClient(ClientDTO client, UserDTO user)
    {
        var _clientRepo = ((UnitOfWork)_unitOfWork).ClientRepository;
        var _client = _clientRepo.Get(filter: u => u.Id == client.Id).Single();

        _client.Id = client.Id;
        _client.Phone = client.Phone;
        _client.Address = client.Address;
        _client.Email = client.Email;
        _client.Type = client.Type;
        _client.Name = client.Name;

        object _transaction = _unitOfWork.BeginTransaction();
        try
        {
            _clientRepo.Update(_client);

            _unitOfWork.CommitTransaction(_transaction);
        }
        catch (Exception)
        {
            _unitOfWork.RollbackTransaction(_transaction);

            return client;
        }
        finally
        {
            _unitOfWork.DestroyTransaction(_transaction);
        }
        return client;
    }

而創建的模型是

namespace OptiLeadInfrastructure.Models
{
    public class ClientDTO
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public Nullable<short> Type { get; set; }
        public string logo { get; set; }
        public Nullable<DateTime> CreatedOn { get; set; }
        public string CreatedBy { get; set; }
        public Nullable<DateTime> LastModifiiedOn { get; set; }
        public virtual ICollection<ClientDetailDTO> ClientDetails { get; set; }
    }   public string LastModifiedBy { get; set; }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM