Search code examples
c#.netentity-frameworkentity-framework-4entity-framework-5

Map model to existing database table using Entity Framework


I face some difficulties when attempt to map my class to existing table using Entity Framework. I currently using Code first but a table was created without it and i cannot map it to a model a created.

My class:

 [Table("AgentCallsByPartner")]
public class AgentCallsByPartnerModel
{
    [Key]
    public int AgentCallID { get; set; }

    [Required]
    public DateTime CallDate { get; set; }

    public string CustomerID { get; set; }

    public string AgentNo { get; set; }

    public string AccountCreated { get; set; }

    public string QuoteStarted { get; set; }

    [Required]
    public string GroupName { get; set; }

    [Required]
    public string GroupRollup { get; set; }

}

Context

    public DbSet<AgentCallsByPartnerModel> AgentCallsByPartner { get; set; }

And this is my table

enter image description here

But when I try to get users from the database, I get an exception

DbContext has changed since the database was created....

So what is my mistake? Thanks


Solution

  • you can be perform several way i just describe few way

    From the Tools menu, click Library Package Manager and then Package Manager Console.

    The enable-migrations command creates a Migrations folder in the your project, and it puts in that folder a Configuration.cs file that you can edit to configure Migrations.

    (If you missed the step above that directs you to change the database name, Migrations will find the existing database and automatically do the add-migration command. That's OK, it just means you won't run a test of the migrations code before you deploy the database. Later when you run the update-database command nothing will happen because the database will already exist.)

    more detail migration http://www.codeproject.com/Articles/801545/Code-First-Migrations-With-Entity-Framework

    another way :

    How to recreate database in EF if my model changes?

    Note: if you use migration then do not lose data value most of time

    Update:

    problem in migration process run the flowing command

    Add-Migration Initial -IgnoreChanges

    Update-Database -verbose