代码优先:将实体映射到现有的数据库表 [英] Code-first: Mapping entities to existing database tables

查看:115
本文介绍了代码优先:将实体映射到现有的数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



通常情况下,我将使用数据库 - 数据库,第一种方法和我的实体和上下文代码生成,但使用设计师已经成为一个巨大的痛苦。



我已经设置了Database.SetInitializer(null),因为我不希望EF更改我的模式。



数据库架构





代码优先:

 code> public class Project 
{
public int ProjectId {get;组; }

public string Name {get;组; }

public string描述{get;组;


public class ReleaseControlContext:DbContext
{
public ReleaseControlContext()
:base(ConfigurationManager.ConnectionStrings [ReleaseControl]。ConnectionString)
{
Database.SetInitializer< ReleaseControlContext>(null);
}

public DbSet< Project>项目{get;组; }
}

致电代码

  using(var context = new ReleaseControlContext())
{
var projects = context.Projects.ToList();
}

抛出以下异常:


SqlException:无效的对象名称'dbo.Projects'。


这是因为我的数据库表是项目而不是项目。我不想将我的上下文的 DbSet< Project> 重命名为Project,因为这在语义上是不正确的。



问题:



我必须使用流畅的API /数据注释来在项目数据库之间进行映射表和 DbSet< Project>项目集合?

解决方案

您可以使用

  [Table(Project)] 
public class Project {
....
}

对项目实体的注释,或$ OnModelCreating(DbModelBuilder modelBuilder)调用 modelBuilder.Entity< Project>()。ToTable(Project);



同样的事情。


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.

I have set Database.SetInitializer(null) as I do not want EF to change my schema.

Database schema:

Code-first:

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; }
}

Calling code:

using(var context = new ReleaseControlContext())
{
    var projects = context.Projects.ToList();
}

The following exception is thrown:

SqlException: Invalid object name 'dbo.Projects'.

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.

Question:

Do I have to use the fluent API/data annotations to map between the Project database table and the DbSet<Project> Projects collection?

解决方案

You can use the

[Table("Project")] 
public class 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆