12

I have a database table created 20 years ago in my company, it is only used for journaling, with NO PRIMARY KEY or INDEX. I can't alter that table.

I understood that we need to call HasNoKey() in code first approach.

But how can I apply HasNoKey in this case? Since it is a Database First approach.

1

3 Answers 3

16

In your DbContext class' OnModelCreating method, you do something like this:

modelBuilder .Entity<MyEntity>(builder => { builder.HasNoKey(); builder.ToTable("MY_ENTITY"); }); 

Read more about it here:
https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=fluent-api

Sign up to request clarification or add additional context in comments.

4 Comments

No code first approach. The Database was created 20 years ago.
@sk This should still apply to DB first ... DB first IS code first, it's just that we generate the Entity Types from the DB first, but it should still create a DbContext with a ConfigureModel method in to which we tell the model that this is going on in the DB.
I can't resolve .HasNoKey() on my newly created entity.
7

Use [Keyless] Attribute of model class.

2 Comments

Simpler solution!!!
Which using do you used?
1

The Keyless attribute was the best solution (don't have reputation yet to comment).

You will want to add the Microsoft.EntityFrameworkCore.Abstractions nuget package to the project with your entities.

And: using Microsoft.EntityFrameworkCore;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.