No method to map entity to table in entity framework core

.net c# entity-framework-core

Question

I am using entity framework core in a normal .net project, version 4.7. I know I can do this. The problem is that I can't seem to map an entity to a table because the "ToTable" method doesn't exist. I can't edit the poco or entity classes because they are predefined and generated. So I can't use the attribute. I looked on the internet and everyone seems to use this method to map an entity to a table.

Here is my code:

public class FactsDbContext : DbContext
{
    public DbSet<TblIncident> TblIncidents { get; set; }

    public DbSet<TblAction> TblActions { get; set; }

    public DbSet<TblAddressTypeAlias> TblAddressTypeAliases { get; set; }

    public DbSet<TblCountry> TblCountries { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //these methods don't exist in my case
        modelBuilder.Entity<TblIncident>(entity => entity.ToTable("Incident"));
        modelBuilder.Entity<TblIncident>().ToTable("Incident");
    }
}

I also tried to use IEntityTypeConfiguration with a EntityTypeBuilder but it still don't have access to the map to table method:

public class IncidentConfig : IEntityTypeConfiguration<TblIncident>
{
    public void Configure(EntityTypeBuilder<TblIncident> builder)
    {
        builder.ToTable("Incident");
    }
}
1
2
9/28/2018 8:54:30 AM

Accepted Answer

You can use the below approach. You have to use Table data annotation.

DBContext:

public virtual DbSet<Article> Article { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Article>(b =>
    {
        b.Property(e => e.Property1).HasDefaultValue(true);
        ... //Other properties
    }

Model class:

[Table("Article")]
public class Article
{

You can also use to ToTable in DBContext, but you have to make sure that you have included using Microsoft.EntityFrameworkCore;.

Line modelBuilder.Entity<TblIncident>().ToTable("Incident"); looks correct according to the documentation. https://docs.microsoft.com/en-us/ef/core/modeling/relational/tables#fluent-api

1
9/28/2018 6:41:10 AM

Popular Answer

I looked into the Entity Framework Core repository on GitHub and searched for the method "Totable" inside the repository. It turns out it is defined as an extension method but it is in separate nuget package and library called Microsoft.EntityFrameworkCore.SqlServer

After I downloaded the package I got the Totable method that I need. Still it doesn't make sense to add that method in a separate package for sql server when you already have the "Table" attribute that you can add on entities directly in the entity framework core package.



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