locked
Is it possible Entity framework will support table without primary key? RRS feed

  • Question

  • User-1651604128 posted

    This may be a common question, but I still can not find a better answer, here is my case:

    I have an existing SQL database, and my ASP.net mvc web app will be generated from it (basically using EF database first approach).

    There are a couple of tables without primary key when it was defined, and all columns are allow null value. So I got error when I update model from these tables.

    I am wondering if there is a way to avoid updating the original tables schema by adding primary key as the original table contains huge data, I do not want to lose them.

    Some posts mentioned to create composite keys, but it doesn't work as in my case all columns are allowing null value.

    Any idea to resolve it? thanks in advance. 

    Tuesday, February 5, 2019 3:50 PM

Answers

All replies

  • User475983607 posted

    Use a Raw query.

    https://docs.microsoft.com/en-us/ef/ef6/querying/raw-sql

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 5, 2019 3:52 PM
  • User-474980206 posted

    default EF can only update if there is a primary key. but you can use SqlQuery or ExecuteSqlCommand to do the update.

    note: its really poor design to not have a primary key.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 5, 2019 3:53 PM
  • User475983607 posted

    Oops

    Tuesday, February 5, 2019 3:54 PM
  • User753101303 posted

    Hi,

    The primary key requirement is not unique to EF. It is to make sure you have a way to select one and only one row (so that it can be updated or deleted).

    If writing an UPDATE statement "by hand" what would you write in the WHERE clause to ensure you are updating the row you want ? Is this even possible (you can have two rows with NULL values in all columns, you would change columns in the where clause based on what you know to be unique at a given time ?)

    This is why you are generally supposed to have a pk in each table (unless maybe rare case I never had myself where you really never have to update/delete single rows)...

    Tuesday, February 5, 2019 5:31 PM
  • User1120430333 posted

    You can use the EF backdoor, ADO.NET, SQL Command object and use T-SQL to do things traditionally using EF.

    Tuesday, February 5, 2019 5:40 PM