Set a Primary Key for an Entity without affect database [ Entity Framework ] [ Database First ] RRS feed

  • Question

  • User1236783433 posted

    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.

    Wednesday, July 15, 2020 11:41 AM

All replies

  • User753101303 posted


    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.

    Wednesday, July 15, 2020 12:20 PM
  • User1686398519 posted

    Hi MBARK,

    • You can add a primary key to an entity without affecting the database. Even if you set the primary key for the entity, the error will still appear.
    • The Entity Framework can support table without primary key.By default, EF can only be updated if there is a primary key. But you can use SqlQuery or ExecuteSqlCommand to update.Please refer to Raw SQL Queries for detailed usage.
    • Although the above solution can meet your needs, but from a certain perspective, such a design is not very good.No primary key will hinder many functions in the future.If you can modify your database, it is best to set the primary key in the database.

    Best regards,

    Yihui Sun

    Thursday, July 16, 2020 7:29 AM