Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make string as primary key in entity framework!

I have a legacy table containing employee name and employee id. Now the employee id is in char because it can hold values starting with an alphabet. Employee id is the only unique field available in the table.

Now I am using a view to capture the data from the table (It is in a separate database). But my entity framework is refusing to identify the view due to the lack of int primary key.

Any solution to this would be highly appreciated as I can not touch the legacy table.

like image 359
Arup Chaudhury Avatar asked Jan 22 '10 13:01

Arup Chaudhury


People also ask

Can a primary key be a string?

Yes, from a performance standpoint (i.e. inserting or querying or updating) using Strings for primary keys are slower than integers. But if it makes sense to use string for the primary key then you should probably use it.

How do I set primary key in Entity Framework?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

How do I create a composite primary key in Entity Framework Core?

Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.

What is Dataannotations key attribute?

The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database.


1 Answers

But my entity framework is refusing to identify the view due to the lack of int primary key.

I doubt it. The EF supports strings as PKs.

But views, of course, can't have PKs at all. Which means you have to do some extra work when using them with the EF, especially if you make them updatable. Here's how.

like image 191
Craig Stuntz Avatar answered Nov 15 '22 11:11

Craig Stuntz