code-第一:映射实体现有的数据库表 [英] Code-first: Mapping entities to existing database tables
问题描述
我使用实体框架6 code-先用现有的数据库,但有问题的映射我的实体的数据库表。
I am using Entity Framework 6 code-first with an existing database, but having problems mapping my entities to the database tables.
标准我已经使用的数据库一和有我的实体和上下文code产生的,但使用设计已经成为一个巨大的痛苦。
Normal I have used database-first and had my entity and context code generated, but using the designer has become a huge pain.
我已经设置Database.SetInitializer(空),因为我不想EF改变我的架构。
I have set Database.SetInitializer(null) as I do not want EF to change my schema.
数据库模式:
code-第一:
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class ReleaseControlContext : DbContext
{
public ReleaseControlContext()
: base(ConfigurationManager.ConnectionStrings["ReleaseControl"].ConnectionString)
{
Database.SetInitializer<ReleaseControlContext>(null);
}
public DbSet<Project> Projects { get; set; }
}
调用code:
using(var context = new ReleaseControlContext())
{
var projects = context.Projects.ToList();
}
下面抛出异常:
The following exception is thrown:
SQLEXCEPTION:无效的对象名称dbo.Projects
这是因为我的数据库表的项目的而不是项目的。我不希望我的重新命名上下文的 DbSet&LT;项目&GT;
来项目,因为那将是语义上不正确
This is because my database table is Project and not Projects. I don't want to rename my context's DbSet<Project>
to "Project" because that would be semantically incorrect.
问:
我必须用流利的API /数据注释到的项目的数据库表和 DbSet℃之间映射;项目&GT;项目
收藏?
Do I have to use the fluent API/data annotations to map between the Project database table and the DbSet<Project> Projects
collection?
推荐答案
您可以使用
[Table("Project")]
public class Project {
....
}
注释对项目实体。
annotation against the Project entity.
在 OnModelCreating(DbModelBuilder模型构建器)
您可以致电
modelBuilder.Entity<Project>().ToTable("Project");
既会做同样的事情
both would do the same thing
这篇关于code-第一:映射实体现有的数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!