简体   繁体   中英

How should I update a table that is joined with another table in Entity Framework?

I have the following entities:

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; }
  }
}

And I have the following api model:

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; }
  }
}

The GET method is implemented successfully as following:

/ 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,
    });
}

Thus far, I have implemented the PUT method as following:

// 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);
}

And a sample payload:

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

How can I update or add a record to PatchFile entity if I only have the PatchNumber and not the PatchId to prevent conflicted with the FOREIGN KEY constraint?

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

Is above the correct approach? If yes, Is this not making another trip to database? Is there a better approach?

You could add the PatchID to the SomeFilesViewModel along the PatchNumber. Otherwise there will be this extra query to the DB. On the other hand: this might create another possible problem, as the sent data don't have to be accurate and you'll need to check/validate it and that would be another trip to DB.

If you decide to stick with the extra query I would suggest rewriting it as following:

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

That way you get only the ID from the DB; assuming you don't need to work with other parts of your Patch object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM