2

I am using .NET core 6. I want t insert data in SQL server without a PK. I have used "KeyLess" and "HasNoKey()". But when i am trying to insert data into DB it is showing me error. Can anyone please tell how to insert without PK?

Error:

"unable to track an instance of type 'entityModel' because it does not have a primary key. only entity types with a primary key may be tracked.'"

4
  • Edit your question and include the text of the error you are being shown. Commented Jul 14, 2022 at 6:01
  • 1
    No you can't because Entity Framework needs to know the key to keep track on the object when you make an update or delete operation. Hence it's not a good idea to have a table without a PrimaryKey. However, KeyLess is used for a different purpose. They can only contain reference navigation properties pointing to regular entities. Commented Jul 14, 2022 at 6:04
  • 1
    The official documentation for keyless says "Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.". I don't see how we can overcome a constraint put by the framework designers. Commented Jul 14, 2022 at 7:23
  • 1
    I'm facing this limitation over and over again. It is the most weird thing that those framework developers are designing EF Core with so many unnecessary rules and behaviors. Developers are wasting enormous amounts of time trying to figure this out. Commented Feb 17, 2023 at 8:28

1 Answer 1

6

Always the entity has a primary key or a compound primary key.

Use compound primary key like this:

modelBuilder.Entity<UserRole>().HasKey(x => new { x.UserId, x.RoleId });
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me, but might not suit every situation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.