187

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?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Cris
  • 12,124
  • 27
  • 92
  • 159
  • 24
    To quote Joe Celko: *if it doesn't have a primary key, it's not a table*. Why on earth would anyone create a "regular" table without a primary key?? Just add those PK! You'll need them - rather sooner than later.... – marc_s Oct 22 '10 at 12:55
  • 4
    If its a view this hava a look this case http://stackoverflow.com/a/10302066/413032 – Davut Gürbüz Apr 24 '12 at 16:32
  • If there are no unique columns, you could always add an identity column and make it the PK. – jrummell Aug 23 '12 at 14:43
  • 60
    It's perfectly valid that not every table needs a primary key. Not often useful, but valid. Confusing EF is one good reason, not that it takes much. ;-). – Suncat2000 Jan 18 '13 at 21:39
  • 30
    Imagine that I can't modify the DB structure on my company and it was created by somebody that wont change the table structure, this scenario is possible. – Tito May 15 '15 at 08:43
  • 4
    This is exactly where we are at. We have to work with a 3rd party Oracle database that has no primary keys. – David Brower May 03 '16 at 15:47
  • 2
    Fact tables in data warehousing are examples of tables that may not have any use of a primary key. See this answer http://stackoverflow.com/a/21298708/1071200 – Lars Gyrup Brink Nielsen Dec 15 '16 at 14:38
  • @marc_s, I've seen that quote attributed to Joe Celko before, but I actually fail to find evidence that he actually said it. Can you please help me? Can you provide me the name of the book or blog where he said so? Thank you! – Luis Gouveia Apr 08 '19 at 16:12

20 Answers20

106

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

Community
  • 1
  • 1
Colin
  • 1,987
  • 3
  • 17
  • 21
  • 6
    +1 This is the right answer, in a perfect world it would be great to go in and modify all legacy databases to have referential integrity, but in reality that's not always possible. – Dylan Hayes May 01 '13 at 17:48
  • 9
    I wouldn't recommend this. Paricularly the ISNULL part. If EF detects two PKs the same, it might not render the unique record(s), and instead return a shared object. This has happened to me before. – Kind Contributor Aug 19 '13 at 03:17
  • @Todd -- how could that ever happen if MyPrimaryID is a NOT NULL column? – JoeCool Oct 10 '14 at 15:05
  • @JoeCool, just because it's NOT NULL doesn't mean it IS unique. I upvoted "THIS SOLUTION WORKS...", because not matter what context it's used in, you can be assured uniqueness. Although thinking about it now, if a record is deleted that will effectively change the following records' "PK". – Kind Contributor Oct 11 '14 at 03:33
  • 1
    -1, because this doesn't answer how to configure Entity Framework/C# code to deal with how to map to a table that lacks an identity seed. Some 3rd party software is (for some reason) written this way. – Andrew Gray Jan 27 '17 at 22:50
66

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Dave Markle
  • 95,573
  • 20
  • 147
  • 170
  • 58
    Agree in common senarios but in rare senarios like LOG table you just need to insert records ASAP. Having PK can be an issue when checking uniqueness and indexing happens. Also If your PK is IDENTITY so returning the generated value to the EF is another issue. using GUID instead? generation time and indexing/sorting is another issue!...SO IN some critical OLTP senarios(like Logging) having no PK is a point and having it has not any positive point! – Mahmoud Moravej Jan 29 '12 at 22:18
  • 5
    @MahmoudMoravej: First off, don't mix up the ideas of clustering indexes and primary keys. They aren't the same thing. You can have very highly performant inserts on tables with clustered indicies on IDENTITY columns. If you run into issues with index maintenance, you should partition the table properly. Leaving a table with no clustered index also means that you can't defragment it effectively to reclaim space after deletes. I pity the poor person who tries to query your logging table if it has no indexes. – Dave Markle Jan 30 '12 at 04:08
  • 1
    Thanks Dave, you made me to rethink :-) .I didn't know that we can have non-clustered PKs (Although its performance is less than clusterd-one in uniqueness check,isn't it?. specially in IDENTITY PK when the new insert will be put at the end of table space). – Mahmoud Moravej Jan 30 '12 at 11:16
  • 2
    You can have a non-clustered PK, and I often do in certain cases. For example, in logging situations, my PK might be an IDENTITY, but my clustered index will often be on the Time, since clustering by Time speeds up range scans. It's often a good idea to partition such tables by Time as well. In this way, you can choose to only do index maintenance and scans (as needed) on the latest partition. As far as insert performance goes, you're correct in that inserts can be faster with unindexed tables, but querying is much slower. – Dave Markle Jan 30 '12 at 14:11
  • 166
    "Fix your data model" isn't a real answer. Sometimes we have to live with less-than-ideal situations we did not create and cannot change. And, as @Colin said, there IS a way to do exactly what the OP was asking. – TheSmurf Nov 26 '12 at 21:38
  • 17
    Changing the code to satisfy EF is a workaround in itself. Not all tables need a primary key nor they should be forced to. E.g. you've a Topic and it has 0 or many keywords. The keywords table can have a parent topic id and a corresponding keyword. TO say that I need to remodel my DB becasue EF forces me to is lame. – Mrchief Dec 19 '12 at 04:50
  • 1
    @Mrchief: You most certainly can have a *composite* primary key in that scenario, where the TopicID and the keyword together comprise the PK of the table. – Dave Markle Dec 19 '12 at 16:02
  • 1
    I can, but then I'll have to live with the overhead of indexing/maintaining/[checking for uniqueness while inserting a new row] for the composite primary key which is uncalled for. A composite index is also slower and bulkier than having an index on just the userId field, which doesn't have to be unique. – Mrchief Dec 19 '12 at 18:22
  • 1
    And its not just EF, I think nHiberante also has this limitation. This is an edge case but not so much. And I really feel this is one of those cases where using a tool becomes an impediment rather than a help. – Mrchief Dec 19 '12 at 18:25
  • So they keep making one mistake after another? Of course, inserting primary key to every table is the the solution to all their problems! – Mrchief Dec 20 '12 at 21:37
  • 1
    Sometimes adding a primary key to the schema is not a solution, like when the data is actually a view into a linked server. There might _be_ a non-null field that EF can't recognize. Colin's solution works. – Tim Apr 03 '13 at 21:41
  • 2
    @Tim: Not sure what you mean by "not a solution". Having a production, non-staging, permanent table without at least one candidate key is *always a problem*, so choosing an appropriate candidate key is by definition *always a solution*. To the downvoters out there, feel free to downvote this, but the OP asked about a *Table*, not a view. And to that specific question, this answer remains the best advice. – Dave Markle Apr 23 '13 at 11:17
  • Your answer is accepted and deserves it. I was not only using a view to get the data, I was getting it from a COTS application whose schema I did not control. While I personally prefer to have all PKs and FKs declared in the database, I don't have that freedom in this situation, even on the base tables. In that case, Colin has a solution that will still work. I believe both answers are valuable contributions. – Tim Apr 24 '13 at 21:00
  • 20
    This should be downvoted because it doesn't answer the question. We often need to work with third party databases that cannot be changed. – Kurren Aug 13 '14 at 16:40
  • @DaveMarkle it's remarkable you have 70k reputation and this kind of attitude. You don't know every situation and there are valid exceptions to every rule. I'm replacing a crap piece of software from CSC that has no PKs and no FKs. It's insane. But long story short, I can depend on no schema changes until the replacement is built but I can't change the schema myself. So the question "can I query the data with EF somehow?" is still valid. Just answer the bleeping question! And obviously the answer isn't "NO" since others have posted a viable solution. – pbristow Jan 04 '18 at 12:06
  • 1
    @pbarranis: Generally I would recommend against writing new EF based applications off of a database which is in such a bad state. The best advice in the OP's scenario is to specify a primary key, and not to do the workaround. That might not be the best advice for your particular situation. Chances are, however, that if your database is of nontrivial size and it has no candidate keys defined, a nontrivial EF-based application will suffer some nasty performance problems if you continue down this path. I wish you good luck. – Dave Markle Jan 04 '18 at 20:17
  • 1
    @DaveMarkle oh no, you couldn't pay me enough to write a new "application" (meaning something long-term and not throw-away) on a DB without PKs and FKs. I'm writing a very simple console app to import the data once so the old CSC app can be given the boot. – pbristow Jan 05 '18 at 20:52
  • What if one wants read-only access? The need for a PK is obvious for adding and updating data and maintaining integrity, but is is really necessary for read-only? – douglas.kirschman Sep 03 '19 at 19:45
  • 3
    Conforming to EF6 is not the same as conforming to SQL server (etc). The answer is still valid, but you can't honestly agree it's the correct decision without precluding yourself from all other factors. I wish the answer was instead "here's how you do it", rather than "don't do it". But it's not. – Barry Sep 19 '19 at 00:33
  • -1 because this is a classic case of a sort of inverted X/Y problem: the question is specifically: how do I do this _without_ adding a PK. This answer says, "add a PK". – Ben Collins Feb 19 '20 at 15:50
  • 1
    @Ben Collins: As an analogy: “How do I wire an electrical outlet with this lamp cord I have? I really don’t want to go to the hardware store and get the right wire.” Sometimes, the only answer is simply, “You don’t. You go to the hardware store and get the right wire.” Yes, you *could* wire an outlet with a lamp cord and yes it *probably* wouldn’t burn the house down and yes the question *could* be answered directly to do the job, but it still wouldn’t be the “right” answer. – Dave Markle Feb 20 '21 at 15:38
36

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; }
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
20

Composite keys can also be done with Entity Framework Fluent API

public class MyModelConfiguration : EntityTypeConfiguration<MyModel>
{
     public MyModelConfiguration()
     {
        ToTable("MY_MODEL_TABLE");
        HasKey(x => new { x.SourceId, x.StartDate, x.EndDate, x.GmsDate });
        ...
     }
}
Adrian Garcia
  • 363
  • 3
  • 12
  • In this sort of 'manual mapping' case, I found that specifying a custom key as you show is effective; additionally, if you don't have the benefit of a composite key (as shown in this answer) you can tag a `modelBuilder.Entity()` chain-call with `.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)` for those oh-so-special keys that aren't natural or composite, but able to be relied upon to be unique (usually, anyways.) – Andrew Gray Jan 27 '17 at 22:48
6

In EF Core 5.0, you will be able to define it at entity level also.

[Keyless]
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public int Zip { get; set; }
}

Reference: https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#use-a-c-attribute-to-indicate-that-an-entity-has-no-key

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • 1
    This needs to be the top answer. [Keyless] above the class definition works perfectly!! Thank you! One of the top answers says to use DbQuery instead of DbSet. That causes the table to be null. – iPaul Apr 10 '23 at 17:59
5

In my case I had to map an entity to a View, which didn't have primary key. Moreover, I wasn't allowed to modify this View. Fortunately, this View had a column which was a unique string. My solution was to mark this column as a primary key:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[StringLength(255)]
public string UserSID { get; set; }

Cheated EF. Worked perfectly, no one noticed... :)

Boris Lipschitz
  • 9,236
  • 5
  • 53
  • 63
  • no.. It will create the `UserID` column if you using the Code First approach..! – Deepak Sharma Oct 22 '14 at 18:05
  • 1
    You have not cheated EF. You just commanded to switch off `Itentity` function. Basically, if I'm correct, It's still going to create `UserID` column for you as PK but it will not automatically increase the `UserID` when you create a new record as would be by default. Also, you still need to keep distinct values in `UserID`. – Celdor Jan 27 '15 at 10:56
  • 1
    @Celdor UserSID is a string, it would never get "automatically increased". If it was an integer identity column then the database would increment it on insert, not Entity Framework. – reggaeguitar Jul 07 '17 at 16:03
4

Having a useless identity key is pointless at times. I find if the ID isn't used, why add it? However, Entity is not so forgiving about it, so adding an ID field would be best. Even in the case it's not used, it's better than dealing with Entity's incessive errors about the missing identity key.

IyaTaisho
  • 863
  • 19
  • 42
4

EF does not require a primary key on the database. If it did, you couldn't bind entities to views.

You can modify the SSDL (and the CSDL) to specify a unique field as your primary key. If you don't have a unique field, then I believe you are hosed. But you really should have a unique field (and a PK), otherwise you are going to run into problems later.

Erick

Erick T
  • 7,009
  • 9
  • 50
  • 85
  • This avoids the ISNULL hack. But depending on the situation, other answers may be required - I have a feeling that some data types are not supported for a PK in EF for example. – Kind Contributor Oct 11 '14 at 03:35
3

THIS SOLUTION WORKS

You do not need to map manually even if you dont have a PK. You just need to tell the EF that one of your columns is index and index column is not nullable.

To do this you can add a row number to your view with isNull function like the following

select 
    ISNULL(ROW_NUMBER() OVER (ORDER BY xxx), - 9999) AS id
from a

ISNULL(id, number) is the key point here because it tells the EF that this column can be primary key

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Barny
  • 383
  • 1
  • 3
  • 13
  • 2
    I wouldn't suggest the ISNULL part though. If EF detects two PKs the same it might not render the unique record, and instead return a shared object. This has happened to me before. – Kind Contributor Aug 19 '13 at 03:15
  • 1
    You have to use isnull, otherwise EF will not beleve that it is not nullable. – Archlight Feb 25 '14 at 15:19
3

This is just an addition to @Erick T's answer. If there is no single column with unique values, the workaround is to use a composite key, as follows:

[Key]
[Column("LAST_NAME", Order = 1)]
public string LastName { get; set; }

[Key]
[Column("FIRST_NAME", Order = 2)]
public string FirstName { get; set; }

Again, this is just a workaround. The real solution is to fix the data model.

Developer
  • 435
  • 4
  • 16
3

This maybe to late to reply...however...

If a table does't have a primary key then there are few scenarios that need to be analyzed in order to make the EF work properly. The rule is: EF will work with tables/classes with primary key. That is how it does tracking...

Say, your table 1. Records are unique: the uniqueness is made by a single foreign key column: 2. Records are unique: the uniqueness are made by a combination of multiple columns. 3. Records are not unique (for the most part*).

For scenarios #1 and #2 you can add the following line to DbContext module OnModelCreating method: modelBuilder.Entity().HasKey(x => new { x.column_a, x.column_b }); // as many columns as it takes to make records unique.

For the scenario #3 you can still use the above solution (#1 + #2) after you study the table (*what makes all records unique anyway). If you must have include ALL columns to make all records unique then you may want to add a primary key column to your table. If this table is from a 3rd party vendor than clone this table to your local database (overnight or as many time you needed) with primary key column added arbitrary through your clone script.

Sam Saarian
  • 992
  • 10
  • 13
2

The above answers are correct if you really don't have a PK.

But if there is one but it is just not specified with an index in the DB, and you can't change the DB (yes, i work in Dilbert's world) you can manually map the field(s) to be the key.

Poker Villain
  • 241
  • 1
  • 5
2

Update to @CodeNotFound's answer.

In EF Core 3.0 DbQuery<T> has been deprecated, instead you should use Keyless entity types which supposedly does the same thing. These are configured with the ModelBuilder HasNoKey() method. In your DbContext class, do this

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<YourEntityType>(eb =>
        {
            eb.HasNoKey();
        });

}

There are restrictions though, notably:

  • Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
  • Only support a subset of navigation mapping capabilities, specifically:
    • They may never act as the principal end of a relationship.
    • They may not have navigations to owned entities
    • They can only contain reference navigation properties pointing to regular entities.
    • Entities cannot contain navigation properties to keyless entity types.

This means that for the question of

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?

You cannot modify data this way - however you can read. One could envision using another way (e.g. ADO.NET, Dapper) to modify data though - this could be a solution in cases where you rarely need to do non-read operations and still would like to stick with EF Core for your majority cases.

Also, if you truly need/want to work with heap(keyless) tables - consider ditching EF and use another way to talk to your database.

Peter Lindsten
  • 539
  • 4
  • 8
1
  1. Change the Table structure and add a Primary Column. Update the Model
  2. Modify the .EDMX file in XML Editor and try adding a New Column under tag for this specific table (WILL NOT WORK)
  3. Instead of creating a new Primary Column to Exiting table, I will make a composite key by involving all the existing columns (WORKED)

Entity Framework: Adding DataTable with no Primary Key to Entity Model.

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
Pratap
  • 183
  • 1
  • 2
1

You can have a composite key setup (similar to how VIEWS are done in EF), and apply both key and column order to the fields so that the combination is unique, EF doesn't need a PK (only useful, if doing insert, update or delete operations) to start with, here's an example of a recent implementation:

[Key]
[Column(Order = 0)]
public int NdfID { get; set; }

[Key]
[Column(Order = 1)]
public int? UserID { get; set; }

[Key]
[Column(Order = 2)]
public int ParentID { get; set; }

In this example, my userid field does contain nulls but with the combination of these three all rows are now unique.

Edited this after years :)

Azerax
  • 41
  • 1
  • 8
0

From a practical standpoint, every table--even a denormalized table like a warehouse table--should have a primary key. Or, failing that, it should at least have a unique, non-nullable index.

Without some kind of unique key, duplicate records can (and will) appear in the table, which is very problematic both for ORM layers and also for basic comprehension of the data. A table that has duplicate records is probably a symptom of bad design.

At the very least, the table should at least have an identity column. Adding an auto-generating ID column takes about 2 minutes in SQL Server and 5 minutes in Oracle. For that extra bit of effort, many, many problems will be avoided.

Ash8087
  • 643
  • 6
  • 16
  • My application is in a data warehouse setting (with Oracle) and you convinced me to go through the 5 minutes to add an index. It really only takes 5 minutes (or slightly more if you need to [look it up](http://stackoverflow.com/questions/11464396/add-a-auto-increment-primary-key-to-existing-table-in-oracle) or modify ETLs). – Trent Jan 20 '16 at 18:36
0

I learned my lesson by working around it. The short answer is DO NOT work around it.

I used EF6 to read a table without a PK but having a compound key. Multiple rows with the same compound key would have the exactly same record. Essentially only one row has been read but used to fill all rows. Since there were million records and it only occurred for a relatively small amount of records which made it very difficult to find the issue.

Cheng
  • 1
0

We have a table without a unique ID column. Other columns were expected to create a composite key, but over time the data has sometimes not had values in all composite key columns.

Here is a solution using the .NET Entity Framework:

[Key]
[Column(Order = 1)]
public Guid FakeId { get; set; }
public ... other columns

And change the SQL to select this:

SELECT NEWID() as FakeId, ... other columns
Joe Kahl
  • 31
  • 5
0

Late answer here. If you can add a Key - you should. EntityFramework uses it internally. I've seen issues - If you have 2 or more identical rows, it'll only come back once. If that's not an option, You need to make an in-memory composite key. You can do this via the Fluent API in the DbContext or in the class mapping.

Option #1:
In your DbContext to make an in-memory composite key with the Fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        modelBuilder.Entity<YOUR_TABLE>()
            .HasKey(c => new { c.Column1, c.Column2, c.Column3, etc. });
}

Option #2:
Same thing but with attributes in EF Object Mapping.

 public class TableName
{
    [Key]
    [Column(Order = 0)]
    public int Column1 { get; set; }
    
    [Key]
    [Column(Order = 1)]
    public int? Column2 { get; set; }
    
    [Key]
    [Column(Order = 2)]
    public int Column3 { get; set; }
}

Option #3:
If you're in EF Core 3.0+ use the fluent API:

modelBuilder
    .Entity<YourEntityType>(eb =>
    {
        eb.HasNoKey();
    });

Option #5:
If you're in EF Core 5.0+ you can do it directly in the EF Object Mapping

[Keyless]
public class TableName
{
    [Key]
    [Column(Order = 0)]
    public int Column1 { get; set; }
    
    [Key]
    [Column(Order = 1)]
    public int? Column2 { get; set; }
    
    [Key]
    [Column(Order = 2)]
    public int Column3 { get; set; }
}
MGot90
  • 2,422
  • 4
  • 15
  • 31
-8

The table just needs to have one column that does not allow nulls