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












0















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?










share|improve this question

























  • Shouldn't you just get all Patch by the number and filter by the FileId of PatchFile? We cannot know, though, we need more data to help you

    – Camilo Terevinto
    Nov 23 '18 at 18:30













  • @CamiloTerevinto I have provided more info. I hope this explains better.

    – amindomeniko
    Nov 23 '18 at 18:52
















0















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?










share|improve this question

























  • Shouldn't you just get all Patch by the number and filter by the FileId of PatchFile? We cannot know, though, we need more data to help you

    – Camilo Terevinto
    Nov 23 '18 at 18:30













  • @CamiloTerevinto I have provided more info. I hope this explains better.

    – amindomeniko
    Nov 23 '18 at 18:52














0












0








0








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?










share|improve this question
















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?







c# entity-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 19:14







amindomeniko

















asked Nov 23 '18 at 18:23









amindomenikoamindomeniko

11311




11311













  • Shouldn't you just get all Patch by the number and filter by the FileId of PatchFile? We cannot know, though, we need more data to help you

    – Camilo Terevinto
    Nov 23 '18 at 18:30













  • @CamiloTerevinto I have provided more info. I hope this explains better.

    – amindomeniko
    Nov 23 '18 at 18:52



















  • Shouldn't you just get all Patch by the number and filter by the FileId of PatchFile? We cannot know, though, we need more data to help you

    – Camilo Terevinto
    Nov 23 '18 at 18:30













  • @CamiloTerevinto I have provided more info. I hope this explains better.

    – amindomeniko
    Nov 23 '18 at 18:52

















Shouldn't you just get all Patch by the number and filter by the FileId of PatchFile? We cannot know, though, we need more data to help you

– Camilo Terevinto
Nov 23 '18 at 18:30







Shouldn't you just get all Patch by the number and filter by the FileId of PatchFile? We cannot know, though, we need more data to help you

– Camilo Terevinto
Nov 23 '18 at 18:30















@CamiloTerevinto I have provided more info. I hope this explains better.

– amindomeniko
Nov 23 '18 at 18:52





@CamiloTerevinto I have provided more info. I hope this explains better.

– amindomeniko
Nov 23 '18 at 18:52












1 Answer
1






active

oldest

votes


















1














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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53451432%2fhow-should-i-update-a-table-that-is-joined-with-another-table-in-entity-framewor%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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.






    share|improve this answer




























      1














      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.






      share|improve this answer


























        1












        1








        1







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 14:01









        MartyMarty

        18416




        18416
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53451432%2fhow-should-i-update-a-table-that-is-joined-with-another-table-in-entity-framewor%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'