问题描述
我在现有数据库中使用 Entity Framework 6 代码优先,但在将我的实体映射到数据库表时遇到问题.
I am using Entity Framework 6 code-first with an existing database, but having problems mapping my entities to the database tables.
通常,我会使用数据库优先的方法并生成我的实体和上下文代码,但使用设计器已成为一个巨大的痛苦.
Normally, I would use database-first approach and have my entity and context code generated, but using the designer has become a huge pain.
我已设置 Database.SetInitializer(null),因为我不希望 EF 更改我的架构.
I have set Database.SetInitializer(null) as I do not want EF to change my schema.
数据库架构:
代码优先:
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; }
}
调用代码:
using(var context = new ReleaseControlContext())
{
var projects = context.Projects.ToList();
}
抛出以下异常:
SqlException:对象名称dbo.Projects"无效.
这是因为我的数据库表是 Project 而不是 Projects.我不想将上下文的 DbSet<Project>
重命名为Project",因为这在语义上是不正确的.
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/数据注释在 Project 数据库表和 DbSet<Project> 之间进行映射?项目
合集?
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 {
....
}
针对 Project 实体的注解,或者在 OnModelCreating(DbModelBuilder modelBuilder)
中您可以调用 modelBuilder.Entity
.
annotation against the Project entity, or in the OnModelCreating(DbModelBuilder modelBuilder)
you can call modelBuilder.Entity<Project>().ToTable("Project");
.
两者都会做同样的事情.
Both would do the same thing.
这篇关于代码优先:将实体映射到现有数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!