Table with no primary key in Entity Framework

.net entity-framework

Question

I want to use an existing database with EF4.0 to create a new app.

I see the following notice when I build a new entity data model since certain tables do not have primary keys declared: "There is no defined primary key for the table/view TABLE NAME, and no valid primary key could be deduced. This table or view was blocked. To use the entity, you will need to review your schema, add the correct keys, and uncomment it".

Is there a solution so that I don't have to add a PK to such tables if I want to utilize them and edit the data?

1
163
4/3/2018 9:18:01 AM

Accepted Answer

The typo clearly conveys its intended meaning.

Trust me, even if you could get past this, you wouldn't want to. Not to mention that your performance will probably suffer, the potential for new, perplexing issues is astounding and terrifying.

Don't try to avoid this. Correct your data model.

EDIT: I've noticed that this question is receiving a lot of negative feedback. The OP asked about mapping a table without a main key, not a view, so I believe that's acceptable. The response remains the same. It is not a good idea to get around the EF's need for PKs on tables from the perspectives of management, data integrity, and performance.

Some people have said that since they are mapping to a third-party application, they are unable to change the underlying data model. That is a bad idea since the model can shift beneath you. In such situation, you may want to map to a view, which is debatably not what the OP asked for.

63
4/3/2018 9:18:35 AM

Popular Answer

I believe Tillito has the answer to this:

SQL Server with Entity Framework View

Below is a quotation from his entry:

This is the answer since we had the same issue:

Utilize ISNULL to have entity framework use a column as a primary key.

Use NULLIF to prevent entity framework from using a column as a primary key.

Applying this is made simple by enclosing your view's choose statement with another select.

Example:

SELECT
  ISNULL(MyPrimaryID,-999) MyPrimaryID,
  NULLIF(AnotherProperty,'') AnotherProperty
  FROM ( ... ) AS temp

Tillito responded at 17:00 on April 26, 2010



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow