如何在EF中的一个查询中选择和更新

时间:2016-12-20 20:54:36

标签: c# entity-framework-6

我有以下查询从表中选择特定列并构造DTO。因为我只需要某些列,所以我没有从数据库中检索所有列。在同一方法中,我还想更新已审核的Entity中的一个特定列,并在返回结果之前将实体保存到数据库。

实体

public class Client
{
   public int ClientID { get; set; }
   public string UploadPath { get; set; }
   public IEnumerable<Batch> Batches { get; set; }
}

public class Batch
{
   public int BatchID { get; set; }
   public int StatusID { get; set; }
}

DTO

public class ClientDTO
{
   public int ClientID { get; set; }
   public string UploadPath { get; set; }
   public IEnumerable<Batch> Batches { get; set;}
}

public class BatchDTO
{
   public int BatchID { get; set; }
   public int StatusID { get; set; }
}   

方式

 public async Task<IEnumerable<ClientDTO>> GetData()
 {
        var query = from r in _dbcontext.Clients
                     select new ClientDTO()
                     {
                         ClientID = r.ClientID,
                         UploadPath = r.UploadPath,
                         Batches = from r1 in r.Batches
                                   select new BatchDTO()
                                   {
                                       BatchID = r1.BatchID,
                                       StatusID = r1.StatusID
                                   }
                     };            

        var result = await query.ToListAsync().ConfigureAwait(false);

        // before returning the result i want to update StatusID column in `Batch` entity. 
        // How do i do that since result is not entity?

        return result;
}

1 个答案:

答案 0 :(得分:1)

您可以创建所需状态的实体,附加它,将属性标记为已更改,然后保存。

var batchToSave = new Batch()
{
    BatchID = whateverYourBatchIdIs,
    StatusID = 234
};
_dbContext.Set<Batch>().Attach(batchToSave);
_dbContext.Entry(batchToSave).Property(x=>x.BatchID).IsModified = true;
_dbContext.SaveChanges();

如果您的批次ID在您检索的内容中,那么您可以选择为要更新的每条记录创建一个并将其全部附加。这样的事情(我没有计算出你的对象图,你必须自己做)。

for (var batchToSave = result.Select(x => new Batch() {BatchID = x.batchId, StatusID = x.status}))
{
    _dbContext.Set<Batch>().Attach(batchToSave);
    _dbContext.Entry(batchToSave).Property(x => x.BatchID).IsModified = true;
}
_dbContext.SaveChanges();

另一方面,如果您只是意味着已检索的批次,它们已被DbContext跟踪。在这种情况下,您可以访问它们并像这样更改它们:

foreach (var batch in _dbContext.ChangeTracker.Entries().OfType<Batch>())
{
    batch.StatusID = 123;
}
_dbContext.SaveChanges();