Code-first: Mapping entities to existing database tables(代码优先:将实体映射到现有数据库表)
问题描述
我在现有数据库中使用 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.
这篇关于代码优先:将实体映射到现有数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代码优先:将实体映射到现有数据库表
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01