I'm doing a project where I have to use EF, but trying to add new data to the table seems to fail every time. I have no knowledge to why/how I can fix it.
The code executing is:
private static void AddCustomer()
{
WriteAdminMenu("Add new customer");
Console.Write("First name: ");
...
WriteAdminMenu("Adding customer...");
using (var db = new EshopContext())
{
db.Addresses.Add(new Address(customerStreet, customerZip, customerCity, customerCountry));
}
}
And I get the following error:
System.InvalidOperationException: No suitable constructor was found for entity type 'Address'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'zip' in 'Address(string street, string zip, string city, string country)'
Context file:
public class EshopContext : DbContext
{
public DbSet<Customer>? Customer { get; set; }
public DbSet<Address>? Addresses { get; set; }
public DbSet<Order>? Orders { get; set; }
public DbSet<Product>? Products { get; set; }
public DbSet<Tag>? Tags { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Data Source=TotallyMyIp;Initial Catalog=MyDatabaseName;Persist Security Info=True;User ID=TotalyMyUserName;Password=totallySecretPassword");
}
And my address model:
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string Zipcode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public Address(string street, string zip, string city, string country)
{
Street = street;
Zipcode = zip;
City = city;
Country = country;
}
}
CodePudding user response:
The framework has no way to know that zip
is the same as Zipcode
.
Keep your names consistent:
public Address(string street, string zipcode, string city, string country)