How to have a primary key with a different name than "Id"

asp.net-core entity-framework-core

Question

I have the following situation in my ASP.NET Core application with Entity Framework Core 1.1

Database-Table named "Content"

  • Content_ID (int not null, primary key)
  • Title (varchar max)
  • Description (varchar max)

Model ("ContentEntry.cs"):

public class ContentEntry
{
    public int Id {get; set;}
    public string Title {get; set;}
    public string Description {get; set;}
}

Configuration File (ContentEntryConfiguration.cs)

public class ContentEntryConfiguration : IEntityMappingConfiguration<ContentEntry>
{
    public void Map(EntityTypeBuilder<ContentEntry> modelBuilder)
    {
        modelBuilder.HasKey(m => m.Id);

        modelBuilder.Property(m => m.Id).HasColumnName("Content_ID");
        modelBuilder.Property(m => m.Title ).HasColumnName("Title");
        modelBuilder.Property(m => m.Description).HasColumnName("Description");

        modelBuilder.ToTable("Content");
    }
}

As mentioned above, the primary key of my table is named "Content_ID". When I execute a LINQ query, I receive an error saying that the column "ID" hasn't been found on the database. After inspecting the generated query with the SQL Profiler, I noticed that the query contains "ID" instead of "Content_ID". I expect entity framework to generate a query containing the column "Column_ID" instead and map it to my model-property named "Id".

Do you have an idea why this is happening and how I could fix this issue?

1
3
1/8/2018 8:27:30 PM

Accepted Answer

I solved it, I just forgot to register the entity mapping in my DB Context Class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.RegisterEntityMapping<ContentEntry, ContentEntryConfiguration>();
}
0
7/10/2017 3:35:14 PM

Popular Answer

For people with simpler needs, this will suffice

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ContentEntry>().Property(c => c.Id).HasColumnName("Content_ID");
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow