[英]How do I get Entity Framework to query the right table?
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. 并且我设置了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. 当我第一次去获取记录时,运行时告诉我数据库表不存在:我检查了一下,发现DbSet的名称与该表不匹配。 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? 我究竟做错了什么?
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. 这会告诉EF您的类的实际表名是什么,否则它将尝试使用类名的复数形式。
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 . 现在覆盖OnMoedlCreateing
方法,以告诉EF使用流畅的API将该类映射到其他表。 Add that method to your DBContext class 将该方法添加到您的DBContext类中
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. 这告诉EF,当您查询DbContxt对象的ReportClasses
属性时,它将从数据库中的ReportClassRealTable
表中获取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.