如何更新与Entity Framework中的另一个表联接的表?

时间:2018-11-23 18:23:47

标签: c# entity-framework

我有以下实体:

namespace SomeDataAccess
{
  public partial class Patch
  {
      public int PatchID { get; set; }
      public double Number { get; set; }
  }

  public partial class PatchFile
  {
      public int FileID { get; set; }
      public int PatchID{ get; set; }
      public string Name { get; set; }
      public string Type { get; set; }
  }
}

我有以下api模型:

namespace Web_API.Models
{
  [Table("SomeFiles")]
  public class SomeFilesViewModel
  {
      [Key]
      public int FileId { get; set; }
      public int PatchNumber{ get; set; }
      public string Name { get; set; }
      public string Type { get; set; }
  }
}

GET方法成功实现如下:

/ GET: api/SomeFiles/5
[ResponseType(typeof(SomeFileViewModel))]
public async Task<IHttpActionResult> GetSomeFileViewModel(int id)
{
  var patchFile = await _context.PatchFile.FindAsync(id);

  return someFile == null
    ? (IHttpActionResult)NotFound()
    : Ok(new someFileViewModel
    {
        FileId = patchFile.FileID,
        PatchNumber = patch.Number,
        Name = patchFile.Name,
        Type = patchFile.Type,
    });
}

到目前为止,我已经实现了以下PUT方法:

// PUT: api/SomeFiles
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutSomeFileViewModel(SomeFilesViewModel someFileViewModel)
{
  if (!ModelState.IsValid)
      return BadRequest(ModelState);

  var file = new SomeDataAccess.PatchFile
  {
      FileID = someFileViewModel.FileId,
      PatchID = _context.Patch.FirstOrDefault(i => i.Number == someFileViewModel.PatchNumber).PatchID
      // How to get the relavent patch id by having the patch Number?
      Name = someFileViewModel.Name,
      Type = someFileViewModel.Type
  };

  _context.Entry(file).State = EntityState.Modified;

  try
  {
    await _context.SaveChangesAsync();
  }
  catch (DbUpdateConcurrencyException)
  {
      if (!FileExists(file.FileID))
        return NotFound();

    throw;
  }

  return StatusCode(HttpStatusCode.NoContent);
}

还有一个样本有效载荷:

Sample PayLoad:
{
  "FileId" = 4
  "PatchNumber" = 894
  "Name" = "MyFile.exe"
  Type = "Application"
}

如果我只有PatchNumber而没有PatchId,那么如何更新记录或向PatchFile实体添加记录,以防止与FOREIGN KEY约束冲突?

_context.Patch.FirstOrDefault(i => i.Number == someFileViewModel.PatchNumber).PatchID 

以上方法是否正确?如果是,这是否不会再次访问数据库?有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以将PatchID沿着PatchNumber添加到SomeFilesViewModel。否则,将向数据库发送此额外查询。另一方面:这可能会带来另一个可能的问题,因为发送的数据不一定准确,您需要检查/验证它,这将是另一次访问数据库的旅程。

如果您决定继续使用多余的查询,建议将其重写为以下内容:

_context.Patch.Where(i => i.Number == someFileViewModel.PatchNumber).Select(i => i.PatchID).FirstOrDefault();

这样,您只能从数据库中获取ID;假设您不需要使用Patch对象的其他部分。