Home > DeveloperSection > Forums > Entity Framework 4.1 code first mapping to already existing database table
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-28-2013 6:29 AM

 ADO.Net ADO.Net 
Ratings:


 1 Reply(s)
 3315  View(s)
Rate this:
I am using Entity Framework 4.1 code first to connect to an already existing database. The table that I am using first is called Bank. I also have a Bank class as my domain model. This is how I mapped my class and table:
public class HbfContext : DbContext
{
     public DbSet<Bank> Banks { get; set; }
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
          modelBuilder.Entity<Bank>().ToTable("Bank");
     }
}

My Bank table:

BankID INT
BankName VARCHAR(50)

My Bank class looks like this:

public class Bank
{
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActive { get; set; }
}

I am having issues when I want to return all the banks. The SQL statement returned from:

return db.Banks
     .OrderBy(x => x.Name);

is:

SELECT
     [Extent1].[Id] AS [Id],
     [Extent1].[Name] AS [Name],
     [Extent1].[IsActive] AS [IsActive]
FROM
     [dbo].[Bank] AS [Extent1]
ORDER BY
     [Extent1].[Name] ASC

This is not going to work because my table does not have the Id, Name and IsActive columns. How would I fix this and would EF map BankId to Id and BankName to Name automatically?



Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    September-28-2013 6:56 AM

Hi Pravesh!

You could use System.ComponentModel.DataAnnotations to map the property names to match those in your existing table e.g.

    [Column("BankID")]
    [Required]
    public string Id
    {
        get;
        set;
    }


Don't want to miss updates? Please click the below button!

Follow MindStick