Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping to already existing database table

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?

like image 980
Brendan Vogt Avatar asked Sep 02 '25 05:09

Brendan Vogt


2 Answers

You need to instruct EF to ignore IsActive property and map other properties. If you don't like data annotations you can do this with fluent API:

modelBuilder.Entity<Bank>().Ignore(b => b.IsActive);
modelBuilder.Entity<Bank>().Property(b => b.Id).HasColumnName("BankID");
modelBuilder.Entity<Bank>().Property(b => b.Name).HasColumnName("BankName");
like image 121
Ladislav Mrnka Avatar answered Sep 05 '25 00:09

Ladislav Mrnka


Try adding the following attribute to the IsActive property and see if it helps

[NotMapped]

UPDATE

Use Data Annotations instead of fluent API which is easier to grasp and use IMO

First of all remove the OnModelCreating function from your context class

Then Define your model like this

[Table("Bank")]
public class Bank
{
    [key]
    public int Id { get; set; }
    [Column("BankName")]
    public string Name { get; set; }
    [NotMapped]
    public bool IsActive { get; set; }
}

This shall work as expected

like image 40
Pankaj Upadhyay Avatar answered Sep 04 '25 23:09

Pankaj Upadhyay