Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Unable to cast object of type 'System.Collections.Generic.List`1[CustomerManager.Model.Customer]' to type 'CustomerManager.Model.Customer'.

Unable to cast object of type 'System.Collections.Generic.List`1[CustomerManager.Model.Customer]' to type 'CustomerManager.Model.Customer'.

Scheduled Pinned Locked Moved C#
comsaleshelp
11 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U uglyeyes

    I am getting this Unable to cast object of type error for below code var cityState = SplitValue(citiesStates[0]); var customers = new List() { new Customer() { CustomerId = 1, FirstName = "bikash", LastName = "shrestha", Email = "bikash@hotmail.com", Address = "482 pacific hwy", City = "Phoenix,AZ", State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 85230, Gender = Gender.Female }, new Customer() { CustomerId = 2, FirstName = "prakash", LastName = "shrestha", Email = "prakash@hotmail.com", Address = "482 pacific hwy", City = "Phoenix,AZ", State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 85231, Gender = Gender.Male } }; customers.ForEach(p => context.Customers.Add(p)); var companies = new List() { new Company() { CompanyId = 1, Name = "abc", Email = "abc@hotmail.com", Address = "xyz street", City = cityState[0], State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 2066, Customers = new List { customers.Single(u => u.CustomerId == 1), customers.Single(u => u.CustomerId == 2) } } }; companies.ForEach(p => context.Companies.Add(p)); <-- here is the error. context.SaveChanges(); My classes ---------- public class Company { public int CompanyId { get; set; } [StringLength(50)] public string Name { get; set; } [StringLength(200)] public string Address { get; set; } [StringLength(500)] public string Email { get; set; } [StringLength(1000)] public string Phone { get; set; } [StringLength(50)

    D Offline
    D Offline
    Dave Kreskowiak
    wrote on last edited by
    #2

    Try adding the Customers, calling SaveChanges on the context, then add the Companies.

    A guide to posting questions on CodeProject

    How to debug small programs
    Dave Kreskowiak

    U 1 Reply Last reply
    0
    • U uglyeyes

      I am getting this Unable to cast object of type error for below code var cityState = SplitValue(citiesStates[0]); var customers = new List() { new Customer() { CustomerId = 1, FirstName = "bikash", LastName = "shrestha", Email = "bikash@hotmail.com", Address = "482 pacific hwy", City = "Phoenix,AZ", State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 85230, Gender = Gender.Female }, new Customer() { CustomerId = 2, FirstName = "prakash", LastName = "shrestha", Email = "prakash@hotmail.com", Address = "482 pacific hwy", City = "Phoenix,AZ", State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 85231, Gender = Gender.Male } }; customers.ForEach(p => context.Customers.Add(p)); var companies = new List() { new Company() { CompanyId = 1, Name = "abc", Email = "abc@hotmail.com", Address = "xyz street", City = cityState[0], State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 2066, Customers = new List { customers.Single(u => u.CustomerId == 1), customers.Single(u => u.CustomerId == 2) } } }; companies.ForEach(p => context.Companies.Add(p)); <-- here is the error. context.SaveChanges(); My classes ---------- public class Company { public int CompanyId { get; set; } [StringLength(50)] public string Name { get; set; } [StringLength(200)] public string Address { get; set; } [StringLength(500)] public string Email { get; set; } [StringLength(1000)] public string Phone { get; set; } [StringLength(50)

      U Offline
      U Offline
      uglyeyes
      wrote on last edited by
      #3

      anyone please?

      1 Reply Last reply
      0
      • D Dave Kreskowiak

        Try adding the Customers, calling SaveChanges on the context, then add the Companies.

        A guide to posting questions on CodeProject

        How to debug small programs
        Dave Kreskowiak

        U Offline
        U Offline
        uglyeyes
        wrote on last edited by
        #4

        I updated the code to be below: but still getting same error

        Company company1 = new Company();
        company1.CompanyId = 1;
        company1.Name = "abc";
        company1.Email = "abc@hotmail.com";
        company1.Address = "xyz street";
        company1.City = cityState[0];
        company1.State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault();
        company1.StateId = 1;
        company1.Zip = 2066;
        company1.Phone = "949494848";
        company1.Customers = new List();

                Customer customer1 = new Customer();
                customer1.CustomerId = 1;
                customer1.FirstName = "bikash";
                customer1.LastName = "shrestha";
                customer1.Email = "bikash@hotmail.com";
                customer1.Address = "482 pacific hwy";
                customer1.City = "Phoenix,AZ";
                customer1.State = sortedStates.Where(state => state.Abbreviation == cityState\[1\]).SingleOrDefault();
                customer1.StateId = 1;
                customer1.Zip = 85230;
                customer1.Gender = Gender.Female;
                customer1.Orders = new List();
        
                Customer customer2 = new Customer();
                customer2.CustomerId = 2;
                customer2.FirstName = "prakash";
                customer2.LastName = "shrestha";
                customer2.Email = "prakash@hotmail.com";
                customer2.Address = "482 pacific hwy";
                customer2.City = "Phoenix,AZ";
                customer2.State = sortedStates.Where(state => state.Abbreviation == cityState\[1\]).SingleOrDefault();
                customer2.StateId = 2;
                customer2.Zip = 85231;
                customer2.Gender = Gender.Male;
                customer2.Orders = new List();
        
                Order order1 = new Order();
                order1.Id = 1;
                order1.CustomerId = 1;
                order1.Product = "apple";
                order1.Date = DateTime.Today;
                order1.Price = 5;
                order1.Quantity = 1;
        
                Order order2 = new Order();
                order2.Id = 2;
                order2.CustomerId = 1;
                order1.Product = "apple";
                order2.Date = DateTime.Today;
                order2.Price = 5;
                order2.Quantity = 1;
        
        
                customer1.Orders.Add(order1);
                customer2.Orders.Add(order2);
                company1.Customers.Add(customer1);
                company1.Customers.Add(customer2);
                
        
                us
        
        D 1 Reply Last reply
        0
        • U uglyeyes

          I updated the code to be below: but still getting same error

          Company company1 = new Company();
          company1.CompanyId = 1;
          company1.Name = "abc";
          company1.Email = "abc@hotmail.com";
          company1.Address = "xyz street";
          company1.City = cityState[0];
          company1.State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault();
          company1.StateId = 1;
          company1.Zip = 2066;
          company1.Phone = "949494848";
          company1.Customers = new List();

                  Customer customer1 = new Customer();
                  customer1.CustomerId = 1;
                  customer1.FirstName = "bikash";
                  customer1.LastName = "shrestha";
                  customer1.Email = "bikash@hotmail.com";
                  customer1.Address = "482 pacific hwy";
                  customer1.City = "Phoenix,AZ";
                  customer1.State = sortedStates.Where(state => state.Abbreviation == cityState\[1\]).SingleOrDefault();
                  customer1.StateId = 1;
                  customer1.Zip = 85230;
                  customer1.Gender = Gender.Female;
                  customer1.Orders = new List();
          
                  Customer customer2 = new Customer();
                  customer2.CustomerId = 2;
                  customer2.FirstName = "prakash";
                  customer2.LastName = "shrestha";
                  customer2.Email = "prakash@hotmail.com";
                  customer2.Address = "482 pacific hwy";
                  customer2.City = "Phoenix,AZ";
                  customer2.State = sortedStates.Where(state => state.Abbreviation == cityState\[1\]).SingleOrDefault();
                  customer2.StateId = 2;
                  customer2.Zip = 85231;
                  customer2.Gender = Gender.Male;
                  customer2.Orders = new List();
          
                  Order order1 = new Order();
                  order1.Id = 1;
                  order1.CustomerId = 1;
                  order1.Product = "apple";
                  order1.Date = DateTime.Today;
                  order1.Price = 5;
                  order1.Quantity = 1;
          
                  Order order2 = new Order();
                  order2.Id = 2;
                  order2.CustomerId = 1;
                  order1.Product = "apple";
                  order2.Date = DateTime.Today;
                  order2.Price = 5;
                  order2.Quantity = 1;
          
          
                  customer1.Orders.Add(order1);
                  customer2.Orders.Add(order2);
                  company1.Customers.Add(customer1);
                  company1.Customers.Add(customer2);
                  
          
                  us
          
          D Offline
          D Offline
          Dave Kreskowiak
          wrote on last edited by
          #5

          OK, now you changed the original post so that there are order. Same problem. Create records for a single table at a time then save the changes. Create the Companies first and save them, then add Orders and save them.

          A guide to posting questions on CodeProject

          How to debug small programs
          Dave Kreskowiak

          U 1 Reply Last reply
          0
          • D Dave Kreskowiak

            OK, now you changed the original post so that there are order. Same problem. Create records for a single table at a time then save the changes. Create the Companies first and save them, then add Orders and save them.

            A guide to posting questions on CodeProject

            How to debug small programs
            Dave Kreskowiak

            U Offline
            U Offline
            uglyeyes
            wrote on last edited by
            #6

            could you please help me? If I first save company first it will be as below

            using (var dbCtx = new CustomerManagerContext())
            {

                        dbCtx.Companies.Add(company1);
                        //call SaveChanges
                        dbCtx.SaveChanges();
                    }
                        company1.Customers.Add(customer1);
                        company1.Customers.Add(customer2);
                        customer1.Orders.Add(order1);
                        customer2.Orders.Add(order2);
            

            how do I now save customer1, customer2 and order1 and order2 using the context?

            D 1 Reply Last reply
            0
            • U uglyeyes

              could you please help me? If I first save company first it will be as below

              using (var dbCtx = new CustomerManagerContext())
              {

                          dbCtx.Companies.Add(company1);
                          //call SaveChanges
                          dbCtx.SaveChanges();
                      }
                          company1.Customers.Add(customer1);
                          company1.Customers.Add(customer2);
                          customer1.Orders.Add(order1);
                          customer2.Orders.Add(order2);
              

              how do I now save customer1, customer2 and order1 and order2 using the context?

              D Offline
              D Offline
              Dave Kreskowiak
              wrote on last edited by
              #7

              I do have a requirement for you when writing code: USE YOUR BRAIN! Serisously? What's preventing you from putting the other creation objects in the same "using" context? NOTHING! You can call SaveChanges multiple times before disposing the CustomerManagerContext. So, create your Customers, SaveChanges. Create your Companies, SaveChanges. Create your Orders, SaveChanges, ... See a pattern there?

              A guide to posting questions on CodeProject

              How to debug small programs
              Dave Kreskowiak

              U 1 Reply Last reply
              0
              • D Dave Kreskowiak

                I do have a requirement for you when writing code: USE YOUR BRAIN! Serisously? What's preventing you from putting the other creation objects in the same "using" context? NOTHING! You can call SaveChanges multiple times before disposing the CustomerManagerContext. So, create your Customers, SaveChanges. Create your Companies, SaveChanges. Create your Orders, SaveChanges, ... See a pattern there?

                A guide to posting questions on CodeProject

                How to debug small programs
                Dave Kreskowiak

                U Offline
                U Offline
                uglyeyes
                wrote on last edited by
                #8

                Ok. I did as per you mentioned but I get below error now

                using (var dbCtx = new CustomerManagerContext())
                {
                dbCtx.Customers.Add(customer1);
                dbCtx.SaveChanges();
                dbCtx.Customers.Add(customer2);
                dbCtx.SaveChanges();
                dbCtx.Companies.Add(company1);
                //call SaveChanges
                dbCtx.SaveChanges();

                             dbCtx.Orders.Add(order1);
                             dbCtx.SaveChanges();
                            dbCtx.Orders.Add(order2);
                             dbCtx.SaveChanges();
                            
                        }
                

                Entities in 'CustomerManagerContext.Customers' participate in the 'Customer_Companies' relationship. 0 related 'Customer_Companies_Target' were found. 1 'Customer_Companies_Target' is expected. this is because I have below method

                protected override void OnModelCreating(DbModelBuilder modelBuilder)
                {

                        modelBuilder.Entity().
                        HasMany(c => c.Companies).
                        WithMany(p => p.Customers).
                        Map(
                        m =>
                        {
                            m.MapLeftKey("CustomerId");
                            m.MapRightKey("CompanyId");
                            m.ToTable("CustomerCompany");
                        });
                        modelBuilder.Entity().HasRequired(c => c.Customers).WithMany().WillCascadeOnDelete(false);
                        modelBuilder.Entity().HasRequired(c => c.Companies).WithMany().WillCascadeOnDelete(false);
                        base.OnModelCreating(modelBuilder);
                    }
                

                sorry still learning entity framework.

                N 1 Reply Last reply
                0
                • U uglyeyes

                  I am getting this Unable to cast object of type error for below code var cityState = SplitValue(citiesStates[0]); var customers = new List() { new Customer() { CustomerId = 1, FirstName = "bikash", LastName = "shrestha", Email = "bikash@hotmail.com", Address = "482 pacific hwy", City = "Phoenix,AZ", State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 85230, Gender = Gender.Female }, new Customer() { CustomerId = 2, FirstName = "prakash", LastName = "shrestha", Email = "prakash@hotmail.com", Address = "482 pacific hwy", City = "Phoenix,AZ", State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 85231, Gender = Gender.Male } }; customers.ForEach(p => context.Customers.Add(p)); var companies = new List() { new Company() { CompanyId = 1, Name = "abc", Email = "abc@hotmail.com", Address = "xyz street", City = cityState[0], State = sortedStates.Where(state => state.Abbreviation == cityState[1]).SingleOrDefault(), Zip = 2066, Customers = new List { customers.Single(u => u.CustomerId == 1), customers.Single(u => u.CustomerId == 2) } } }; companies.ForEach(p => context.Companies.Add(p)); <-- here is the error. context.SaveChanges(); My classes ---------- public class Company { public int CompanyId { get; set; } [StringLength(50)] public string Name { get; set; } [StringLength(200)] public string Address { get; set; } [StringLength(500)] public string Email { get; set; } [StringLength(1000)] public string Phone { get; set; } [StringLength(50)

                  N Offline
                  N Offline
                  Nathan Minier
                  wrote on last edited by
                  #9

                  Okay, you have a little work to do on this. even when using POCOs, you need to keep the shape of the database and the limitations of SQL (like field values in tables) in mind. You still use foreign keys to map to complex types, and you cannot insert values into a SQL field that it does not recognize as a native type. I'm assuming your context class looks like:

                  public class MyContext : DbContext
                  {
                  public DbSet Customers { get; set; }
                  public DbSet Companies { get; set; }
                  public DbSet Orders { get; set; }
                  }

                  You have a M:M mapping for customers to companies, and and 1:M for customers and orders (I'm guessing). without seeing the Order class, it looks like our base structure has an few inherent flaws, and will not be able to normalize or even perform proper data access at the moment. Here's the obvious changes:

                  public class Company
                  {
                  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Display(AutoGenerateField = false)]
                  public int CompanyId { get; set; }

                  [StringLength(50)]
                  public string Name { get; set; }

                  [StringLength(200)]
                  public string Address { get; set; }

                  [StringLength(500)]
                  public string Email { get; set; }

                  [StringLength(1000)]
                  public string Phone { get; set; }

                  [StringLength(50)]
                  public string City { get; set; }

                  public State State { get; set; }
                  public int StateId { get; set; }
                  public int Zip { get; set; }

                  public virtual ICollection Orders{ get; set; } // Change for M:M mapping
                  }

                  public class Customer
                  {
                  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Display(AutoGenerateField = false)]
                  public int CustomerId { get; set; }

                  [StringLength(50)]
                  public string FirstName { get; set; }

                  [StringLength(50)]
                  public string LastName { get; set; }

                  [StringLength(100)]
                  public string Email { get; set; }

                  [StringLength(1000)]
                  public string Address { get; set; }

                  [StringLength(50)]
                  public string City { get; set; }
                  public int Zip { get; set; }

                  //State is not a valid class for the DB. If it's a Table do this
                  [Display(AutoGenerateField = false), ForeignKey("State")]
                  public int StateId { get; set; }
                  public virtual State State { get; set; }

                  public virtual ICollection Orders{ get; set; } // Change for M:M mapping

                  // Gender is not a valid field class. Just use the enum string (or int) value
                  public string Gender { get; set; }

                  Okay, now that the changes are made to those classes, let's look at a possible Orders class. I'll just add the fields to

                  U 1 Reply Last reply
                  0
                  • U uglyeyes

                    Ok. I did as per you mentioned but I get below error now

                    using (var dbCtx = new CustomerManagerContext())
                    {
                    dbCtx.Customers.Add(customer1);
                    dbCtx.SaveChanges();
                    dbCtx.Customers.Add(customer2);
                    dbCtx.SaveChanges();
                    dbCtx.Companies.Add(company1);
                    //call SaveChanges
                    dbCtx.SaveChanges();

                                 dbCtx.Orders.Add(order1);
                                 dbCtx.SaveChanges();
                                dbCtx.Orders.Add(order2);
                                 dbCtx.SaveChanges();
                                
                            }
                    

                    Entities in 'CustomerManagerContext.Customers' participate in the 'Customer_Companies' relationship. 0 related 'Customer_Companies_Target' were found. 1 'Customer_Companies_Target' is expected. this is because I have below method

                    protected override void OnModelCreating(DbModelBuilder modelBuilder)
                    {

                            modelBuilder.Entity().
                            HasMany(c => c.Companies).
                            WithMany(p => p.Customers).
                            Map(
                            m =>
                            {
                                m.MapLeftKey("CustomerId");
                                m.MapRightKey("CompanyId");
                                m.ToTable("CustomerCompany");
                            });
                            modelBuilder.Entity().HasRequired(c => c.Customers).WithMany().WillCascadeOnDelete(false);
                            modelBuilder.Entity().HasRequired(c => c.Companies).WithMany().WillCascadeOnDelete(false);
                            base.OnModelCreating(modelBuilder);
                        }
                    

                    sorry still learning entity framework.

                    N Offline
                    N Offline
                    Nathan Minier
                    wrote on last edited by
                    #10

                    Please remove that OnModelCreating. It's pretty broken; it would require that a customer exist before a company does, and that a company exist before a customer does....

                    1 Reply Last reply
                    0
                    • N Nathan Minier

                      Okay, you have a little work to do on this. even when using POCOs, you need to keep the shape of the database and the limitations of SQL (like field values in tables) in mind. You still use foreign keys to map to complex types, and you cannot insert values into a SQL field that it does not recognize as a native type. I'm assuming your context class looks like:

                      public class MyContext : DbContext
                      {
                      public DbSet Customers { get; set; }
                      public DbSet Companies { get; set; }
                      public DbSet Orders { get; set; }
                      }

                      You have a M:M mapping for customers to companies, and and 1:M for customers and orders (I'm guessing). without seeing the Order class, it looks like our base structure has an few inherent flaws, and will not be able to normalize or even perform proper data access at the moment. Here's the obvious changes:

                      public class Company
                      {
                      [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Display(AutoGenerateField = false)]
                      public int CompanyId { get; set; }

                      [StringLength(50)]
                      public string Name { get; set; }

                      [StringLength(200)]
                      public string Address { get; set; }

                      [StringLength(500)]
                      public string Email { get; set; }

                      [StringLength(1000)]
                      public string Phone { get; set; }

                      [StringLength(50)]
                      public string City { get; set; }

                      public State State { get; set; }
                      public int StateId { get; set; }
                      public int Zip { get; set; }

                      public virtual ICollection Orders{ get; set; } // Change for M:M mapping
                      }

                      public class Customer
                      {
                      [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Display(AutoGenerateField = false)]
                      public int CustomerId { get; set; }

                      [StringLength(50)]
                      public string FirstName { get; set; }

                      [StringLength(50)]
                      public string LastName { get; set; }

                      [StringLength(100)]
                      public string Email { get; set; }

                      [StringLength(1000)]
                      public string Address { get; set; }

                      [StringLength(50)]
                      public string City { get; set; }
                      public int Zip { get; set; }

                      //State is not a valid class for the DB. If it's a Table do this
                      [Display(AutoGenerateField = false), ForeignKey("State")]
                      public int StateId { get; set; }
                      public virtual State State { get; set; }

                      public virtual ICollection Orders{ get; set; } // Change for M:M mapping

                      // Gender is not a valid field class. Just use the enum string (or int) value
                      public string Gender { get; set; }

                      Okay, now that the changes are made to those classes, let's look at a possible Orders class. I'll just add the fields to

                      U Offline
                      U Offline
                      uglyeyes
                      wrote on last edited by
                      #11

                      Hi, thanks for the detailed explaination. In my case, a company can have many customer and a customer can belong to many companies. only customers will have order. Sorry to call this "order". It should actually be called "Job". Would I require making any changes to what you have described above for my situation?

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups