Last post Jul 16, 2020 07:29 AM by YihuiSun
Jul 15, 2020 11:41 AM|MBARK|LINK
I'm working on an ASP.NET MVC project, I use Entity
Framework [ Database First ], I created a data model depend
on SQL server database, I created a Table in the database and I updated the data model from the database, and when I try to add a record
to the new table I created (this table doesn't have a PK) I got an error,
when I search about the error I Understood that in Entity Framework need to have a PK for Entity.
So I ASK if I can set a Primary Key for an Entity without affect database, or any other solution to solve this problem and massive thanks in advance.
Jul 15, 2020 12:20 PM|PatriceSc|LINK
Depends. Do you have already a column that could be used as a pk? If you meant you can't even add a primarty key constraint on the db side you can still lie to EF by using for example
https://www.learnentityframeworkcore.com/configuration/fluent-api/haskey-method to tell which column should be used as a pk. EF won't check the db site but know i can use this value to build UPDATE statements.
Else you may have to add a new column or fix the db side (seems best to have a properly designed db unless this is a shortcoming in a 3rd party database).
Note that the primary key is how you can uniquely identify a row so as soon as you want to update rows in a table it is likely that you do have a primary key in this table even if not explictly declared else you couldn't write an UPDATE query with a WHERE
clause that can change only the row you want.
Jul 16, 2020 07:29 AM|YihuiSun|LINK