Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code-first: Mapping entities to existing database tables

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:

enter image description here

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?

like image 662
Dave New Avatar asked Nov 27 '13 13:11

Dave New


People also ask

Can we use code first with existing database?

This step-by-step walkthrough provides an introduction to Code First development targeting an existing database. Code First allows you to define your model using C# or VB.Net classes. Optionally additional configuration can be performed using attributes on your classes and properties or by using a fluent API.


2 Answers

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.

like image 181
AlexC Avatar answered Nov 16 '22 02:11

AlexC


You should define a class (ie:ProjectMap) that inherits from the generic class EntityTypeConfiguration(T) where T is here your Project class. In this ProjectMap class, you can define explicitly a table mapping :

this.ToTable("Project", "dbo");

The class ProjectMap should be called in the following method of your DbContext class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProjectMap());
}
like image 40
user3041160 Avatar answered Nov 16 '22 04:11

user3041160