Search code examples
c#entity-framework-coredto

Update of Table when I don't have the key value


I am developing a .net core api using entity framework. I have done development for a while but am new to entity framework. In addition I am attempting to implement using DTO objects to restrict and reduce the amount of information available. My problem is this. If I do not pass my unique id from the DB back to the end user how can I perform an update against that object?

For example I have a class that has

ID, FirstName, LastName, Age

My DTO back to the end user is:

FirstName, LastName, Age

How can I implement Update and Delete without the ID?

I know this is probably a dumb question and I am missing the obvious so please be gentle. I have looked for the answer but every time I search I just keep finding questions about tables that don't have a primary key.


Solution

  • You can't update a record without using Id or another primary key. For example to update the user you need to find an existed user record, update some or all properties and save. The only way to find the user without using Id would be

    var existedUser = Context.Set<User>().Where(u=> u.FirstName==dto.FirstName 
    && u.LastName==dto.LastName  
    && u.Age==dto.Age).FirstOrDefault();
    

    but since you have to update user properties it means FirstName or LastName or Age or all of them are changed in your Dto already, so you can't use them to find a user record to update.

    You can use this code to find a user to delete, but it is not the best idea too, since can be a differet user with the same name and age.