Home > Enterprise >  No suitable constructor error in Entity Framework
No suitable constructor error in Entity Framework

Time:10-14

So previously I failed to have a suitable constructor, because of naming violation. This time the naming is identical, yet it still fails.

I get the following error code:

No suitable constructor was found for entity type 'Customer'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'Address' in 'Customer(string firstName, string lastName, Address Address, string email)'.'

With the following execution:

using (var db = new EshopContext())
{
    var test = db.Products
        .Where(p => p.Title == customSearchTag)
        .ToList(); //Error here

    foreach (var item in test)
    {
        Console.WriteLine(item.Title   " for "   item.Price);
    }
}

Address.cs

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 zipcode, string city, string country)
{
    Street = street;
    Zipcode = zipcode;
    City = city;
    Country = country;
}

Customer.cs

public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public string Email { get; set; }

public Customer(string firstName, string lastName, Address Address, string email)
{
    FirstName = firstName;
    LastName = lastName;
    this.Address = Address;
    Email = email;
}    

I hope someone can tell my why this error happens. Because I don't know why it won't bind the property

CodePudding user response:

You need to add an empty constructor to avoid that error.

public class Company
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
    public string Email { get; set; }

    public Customer(string firstName, string lastName, Address Address, string email)
    {
        FirstName = firstName;
        LastName = lastName;
        this.Address = Address;
        Email = email;
    }
    
    // Add this
    public Customer() {}
}
  • Related