none
Getting "The entity type Company is not part of the model for the current context." error trying to do Code First in EF RRS feed

  • Question

  • I have never done ADO.NET nor EF, and am trying to do Code First. I've only watched some of Julie Lerman's videos, so please bear with me.

    Here is the Main program:

    namespace Insperity.Benefits.EFPilot
    {
        class Program
        {
            static void Main(string[] args)
            {
                var db = new ConnStrName();
                DbSet<Company> coDbSet = db.CompanyPluralized;
                foreach (var co in coDbSet)
                {
                    Console.WriteLine(co.LegalName);
                }
                Console.Read();
            }
        }
    }

    I am getting the error at the foreach statement. Below are my 'DbContext' code, connection string, and Domain Classes.

    I came up with the connectionString by using a Model First approach on an existing DB and change the metadata to .\\

    What am I doing wrong?

    Thanks for any pointers. I think I can use a bit of hand holding ...

    namespace Insperity.Benefits.EFPilot { using System.Data.Entity; using System.Data.Entity.Infrastructure; public class ConnStrName : DbContext { public ConnStrName() : base("name=ConnStrName") {} protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public DbSet<Company> CompanyPluralized { get; set; } public DbSet<CompanyClassRestriction> CompanyClassRestrictionPluralized { get; set; } } } <connectionStrings> <add name="ConnStrName" connectionString="metadata=.\\;provider=System.Data.SqlClient;provider connection string=&quot;data source=KWIDBSQLD02\Instance1;initial catalog=Benefits;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> namespace Insperity.Benefits.EFPilot { public class Company{ [Required] public Int32? CompanyId { get; set; } [Required] public Int32? AimsCompanyId { get; set; } public Int32? PackageId { get; set; } [Required] public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public String LegalName { get; set; } [Column("DBAName")] public String DbaName { get; set; } public Int32? WaitPeriod { get; set; } public DateTime? InsuranceEligibilityDate { get; set; } [Column("BenefitStartDate")] public DateTime? BenefitsStartDate { get; set; } public Boolean? IsBundled { get; set; } public String PayrollSpecialist { get; set; } [Required] public DateTime? ChangeDate { get; set; } public String UserId { get; set; } public DateTime? CSPEndDate { get; set; } public String PayrollSpecialistEmail { get; set; } public Boolean? AutoEnrollLifeAdd { get; set; } public Boolean? AutoEnrollDisability { get; set; } public DateTime? OpenEnrollStartDate { get; set; } public DateTime? OpenEnrollEndDate { get; set; } [Required] public Boolean? IsClassed { get; set; } public String BenefitSpecialist { get; set; } public String BenefitSpecialistEmail { get; set; } public Int32? ContractId { get; set; } public DateTime? RenewDate { get; set; } [NotMapped] public DateTime? EnterDateTime { get; set; } [NotMapped] public String TransactionEventType { get; set; } [NotMapped] public String TransactionId { get; set; } [NotMapped] public String DeleteTransactionId { get; set; } [NotMapped] public DateTime? DeleteDate { get; set; } public DateTime? BidDate { get; set; } public Boolean? IsCSP { get; set; } [NotMapped] public Response Response { get; set; } [NotMapped] public String Action { get; set; } [NotMapped] public List<CompanyClassRestriction> CompanyClassRestrictionCollection { get; set; } [NotMapped] public String Id { get; set; } [NotMapped] public Boolean IsDirty { get; set; } [NotMapped] public Object ParentCollection { get; set; } [NotMapped] public ISite Site { get; set; } } public class CompanyClassRestriction { [Required] public Int32? CompanyId { get; set; } [Required] public Int32? ClassTypeId { get; set; } [Required] public Int32? SubClassId { get; set; } [Required] public Int32? CoverageCategoryId { get; set; } [Required] public Boolean? Restricted { get; set; } public String UserId { get; set; } [Required] public DateTime? ChangeDate { get; set; } [NotMapped] public DateTime? EnterDateTime { get; set; } [NotMapped] public String TransactionEventType { get; set; } [NotMapped] public String TransactionId { get; set; } [NotMapped] public String DeleteTransactionId { get; set; } [NotMapped] public DateTime? DeleteDate { get; set; } [NotMapped] public String Action { get; set; } [NotMapped] public String Id { get; set; } [NotMapped] public Boolean IsDirty { get; set; } [NotMapped] public Object ParentCollection { get; set; } [NotMapped] public ISite Site { get; set; } }

    Wednesday, October 3, 2012 8:29 PM

Answers

  • Glenn,

    I am not really using any code from Model First. Just the connectionString from Database First (I mis-spoken initially about using Model First).

    And you're absolutely correct about the exception I'm seeing. Just part of being green in this on my part ... :-(

    I followed that thread, tried a few other things and finally got my current pilot to work. It is actually not complicated at all. I just replaced

     throw new UnintentionalCodeFirstException();

    with

    modelBuilder.Conventions.Remove<

    PluralizingTableNameConvention>();


    and things started to work for me. Thanks to you and daProgramma. (struggling a bit with this text box as you may see ... :-( ) -- Wood

    • Marked as answer by Wood Lee Friday, October 5, 2012 11:41 AM
    Friday, October 5, 2012 11:39 AM

All replies

  • Hello,

    you do not need the metadata-part in your connection string. A connections string for code first should look like this in the app.config:

    <addname="MSSQL"   connectionString="Data Source=whatever;Initial Catalog=test;Integrated Security=True"providerName="System.Data.SqlClient"/>

    and then you instantiate the DBContext like this:

     

    public class Context : DbContext { public Context() : base( "name = MSSQL" ) {} ... }

    ... my 2 cents
    daProgramma


    Thursday, October 4, 2012 6:30 AM
  • Thanks, daProgramma.

    I tried your suggestion, changing the connectionString to:

        <add name="ConnStrName"
             connectionString="data source=KWIDBSQLD02\Instance1;initial catalog=Benefits;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"
             providerName="System.Data.SqlClient" />

    I now get "UnintentionalCodeFirstException was unhandled", with:

    Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.

    Thursday, October 4, 2012 1:53 PM
  • Hi,

    The reason that you are getting an UnintentionalCodeFirstException is because your code explicitly throws it in OnModelCreating. Remove the throw from here:

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                throw new UnintentionalCodeFirstException();
            }
    

    It appears that you have generated code with model first and now are converting to code first, is that correct? If so then the EF Power Tools can be used to generate a code first model instead of following this approach, and may be less confusing. But that line that throws UnintentionalCodeFirst is what is causing your current problem.

    We are seeing a lot of great Entity Framework questions (and answers) from the community on Stack Overflow. As a result, our team is going to spend more time reading and answering questions posted on Stack Overflow. We would encourage you to post questions on Stack Overflow using the entity-framework tag. We will also continue to monitor the Entity Framework forum.

    Thursday, October 4, 2012 6:14 PM
    Moderator
  • Glenn,

    the behavior you see is absolutely correct.

    Hint: Look at your implementation of the OnModelCreating - function. Usualy, special mapping code geos there, if you need it, otherwise don't even overload it.

    ..my 2 cents
    da Programma

    • Proposed as answer by daProgramma Friday, October 5, 2012 11:24 AM
    Friday, October 5, 2012 11:24 AM
  • Glenn,

    I am not really using any code from Model First. Just the connectionString from Database First (I mis-spoken initially about using Model First).

    And you're absolutely correct about the exception I'm seeing. Just part of being green in this on my part ... :-(

    I followed that thread, tried a few other things and finally got my current pilot to work. It is actually not complicated at all. I just replaced

     throw new UnintentionalCodeFirstException();

    with

    modelBuilder.Conventions.Remove<

    PluralizingTableNameConvention>();


    and things started to work for me. Thanks to you and daProgramma. (struggling a bit with this text box as you may see ... :-( ) -- Wood

    • Marked as answer by Wood Lee Friday, October 5, 2012 11:41 AM
    Friday, October 5, 2012 11:39 AM
  • Ok, glad you have it working. The reason I assumed you had started with Model First and copied some code is because that throw exception is generated for you when you create a model. So if you had copied the context that was generated by an edmx model then it would explain why it was there.

    We are seeing a lot of great Entity Framework questions (and answers) from the community on Stack Overflow. As a result, our team is going to spend more time reading and answering questions posted on Stack Overflow. We would encourage you to post questions on Stack Overflow using the entity-framework tag. We will also continue to monitor the Entity Framework forum.

    Friday, October 5, 2012 4:23 PM
    Moderator