Entity Framework: table without primary key
I have an existing DB with which I would like to build a new app using EF4.0
Some tables do not have primary keys defined so that when I create a new Entity Data Model, I get the following message:
The table/view TABLE_NAME does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.
If I want to use them and modify data, must I necessarily add a PK to those tables, or is there a workaround so that I don't have to?
I think this is solved by Tillito:
Entity Framework and SQL Server View
I'll quote his entry below:
We had the same problem and this is the solution:
To force entity framework to use a column as a primary key, use ISNULL.
To force entity framework not to use a column as a primary key, use NULLIF.
An easy way to apply this is to wrap the select statement of your view in another select.
Example:
SELECT
ISNULL(MyPrimaryID,-999) MyPrimaryID,
NULLIF(AnotherProperty,'') AnotherProperty
FROM ( ... ) AS temp
answered Apr 26 '10 at 17:00 by Tillito
The error means exactly what it says.
Even if you could work around this, trust me, you don't want to. The number of confusing bugs that could be introduced is staggering and scary, not to mention the fact that your performance will likely go down the tubes.
Don't work around this. Fix your data model.
EDIT: I've seen that a number of people are downvoting this question. That's fine, I suppose, but keep in mind that the OP asked about mapping a table without a primary key, not a view. The answer is still the same. Working around the EF's need to have a PK on tables is a bad idea from the standpoint of manageability, data integrity, and performance.
Some have commented that they do not have the ability to fix the underlying data model because they're mapping to a third-party application. That is not a good idea, as the model can change out from under you. Arguably, in that case, you would want to map to a view, which, again, is not what the OP asked.
If I want to use them and modify data, must I necessarily add a PK to those tables, or is there a workaround so that I don't have to?
For those reaching this question and are using Entity Framework Core, you no longer need to necessarily add a PK to thoses tables or doing any workaround. Since EF Core 2.1 we have a new feature Query Types
Query types must be used for:
- Serving as the return type for ad hoc FromSql() queries.
- Mapping to database views.
- Mapping to tables that do not have a primary key defined.
- Mapping to queries defined in the model.
So in your DbContext just add the following property of type DbQuery<T>
instead of DbSet<T>
like below. Assuming your table name is MyTable
:
public DbQuery<MyTable> MyTables { get; set; }