I have some EF Core models that were built using dotnet ef dbContext scaffold
to produce models using a database first approach. My problem is the database uses an integer primary key, used for linking tables together but has a string based index that would be used as the sane index for searching the table.
However: When I attempt to use FindAsync("abc000")
I get an entirely expected error The key value at position 0 of the call to 'DbSet<Entity>.Find' was of type 'string', which does not match the property type of 'long'.
So, two questions:
- How did EF Figure out what the primary key was?
- Is there any way I can re-jig this so I can use "Find" to search for entities by name, but keep the autoincrement primary keys?
- Am I being stupid for preferring auto increment integer keys as the fields to join tables on?
They look like this:
class Entity
{
long Id;
string Key;
};
And in OnModelCreating:
modelBuilder.Entity<Entity>(entity =>
{
entity.ToTable("tb_entity", "main");
entity.HasIndex(e => e.Key)
.HasName("uq_entity_key")
.IsUnique();
entity.Property(e => e.Id).HasColumnName("_id");
entity.Property(e => e.Key)
.HasColumnName("key")
.HasMaxLength(255);
}
The SQL that created the tables looks like:
CREATE TABLE [tb_entity]
(
_id BIGINT PRIMARY KEY IDENTITY(1,1),
key NVARCHAR(255) CONSTRAINT uq_entity_key UNIQUE NOT NULL,
);