Last post Feb 05, 2019 05:40 PM by DA924
Feb 05, 2019 03:50 PM|Peter Cong|LINK
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.
Feb 05, 2019 03:52 PM|mgebhard|LINK
Use a Raw query.
Feb 05, 2019 03:53 PM|bruce (sqlwork.com)|LINK
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.
Feb 05, 2019 03:54 PM|mgebhard|LINK
Feb 05, 2019 05:31 PM|PatriceSc|LINK
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)...
Feb 05, 2019 05:40 PM|DA924|LINK
You can use the EF backdoor, ADO.NET, SQL Command object and use T-SQL to do things traditionally using EF.