EF Core Database First HasNoKey
Asked Answered
A

3

11

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.

Aflcio answered 6/2, 2020 at 13:53 Comment(1)
You can check this article learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-typesEventempered
I
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

Idzik answered 6/2, 2020 at 13:58 Comment(4)
No code first approach. The Database was created 20 years ago.Aflcio
@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.Monoculture
I can't resolve .HasNoKey() on my newly created entity.Southernmost
See learn.microsoft.com/en-us/ef/core/modeling/…Idzik
B
6

Use [Keyless] Attribute of model class.

Becka answered 31/1, 2023 at 19:4 Comment(2)
Simpler solution!!!Spracklen
Which using do you used?Robenarobenia
F
0

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;

Flyman answered 12/8 at 0:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.