Unable to cast object of type 'System.Collections.Generic.List`1[CustomerManager.Model.Customer]' to type 'CustomerManager.Model.Customer'.
-
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)
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 -
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)
-
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 KreskowiakI 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
-
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
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 -
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 Kreskowiakcould 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?
-
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?
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 -
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 KreskowiakOk. 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.
-
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)
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
-
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.
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....
-
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
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?