Reputation: 693
I've got a class defined
public class ReportClass
{
public int ID { get; set; }
public int ClassIndex { get; set; }
public string ClassName { get; set; }
public int CompanyID { get; set; }
}
and I set up a dbcontext.
public class ReportClassContext : DbContext
{
public DbSet<ReportClass> ReportClasses { get; set; }
}
When I first went to get records, the runtime tells me the database table doesn't exist: I check, and I see that the name of my DbSet doesn't match with the table. I switched the name to match:
public class ReportClassContext : DbContext
{
public DbSet<ReportClass> ReportClassesRealTable { get; set; }
}
but it is still querying against the non-existent table.
What am I doing wrong?
Upvotes: 0
Views: 1056
Reputation: 218942
Let this be there as it is
public DbSet<ReportClass> ReportClasses { get; set; }
Now overrde the OnMoedlCreateing
method to tell EF to map this class to a different table using fluent API. Add that method to your DBContext class
public class ReportClassContext : DbContext
{
public DbSet<ReportClass> ReportClasses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ReportClass>().ToTable("ReportClassesRealTable");
}
}
This tells EF that when you query ReportClasses
property of your DbContxt object, It will fetch data from teh ReportClassRealTable
table in your database.
Upvotes: 2
Reputation: 19872
Use the table attribute like this:
[Table("ReportClassesRealTable")]
public class ReportClass
{
public int ID { get; set; }
public int ClassIndex { get; set; }
public string ClassName { get; set; }
public int CompanyID { get; set; }
}
This tells the EF what the actual table name is for your class, otherwise it attempts to use the plural form of your class name.
Upvotes: 7