代码优先:将实体映射到现有数据库表

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().ToTable("Project");.

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.

这篇关于代码优先:将实体映射到现有数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)