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.
这篇关于代码优先:将实体映射到现有数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代码优先:将实体映射到现有数据库表
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
