Migration problem with immutable complex type entity for Entity Framework Core 8

Nasir Uddin 41 Reputation points
2024-03-07T10:47:59.4566667+00:00

I am using EF Core 8 in my project. I am trying to use an immutable complex-type entity. Here is my code:

[ComplexType]    
public class Address(string line1, string? line2, string city, string country, string postCode)
{
    [MaxLength(250)]
    [Column("Line1")]
    public string Line1 { get; } = line1;
    [MaxLength(250)]
    [Column("Line2")]
    public string? Line2 { get; } = line2;
    [MaxLength(100)]
    [Column("City")]
    public string City { get; } = city;
    [MaxLength(100)]
    [Column("Country")]
    public string Country { get; } = country;
    [MaxLength(100)]
    [Column("PostCode")]
    public string PostCode { get; } = postCode;
}

And here is my main entity:

public class Customer
{
    public required Guid Id { get; set; }
    public required string Title { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }    
    public Address? Address { get; set; }   
	public ICollection<Account>? Accounts { get; set; } = [];     
}

public class Account
{
    public required Guid Id { get; set; }
    public required string Name { get; set; }
    public required string Email { get; set; }    
    public Address? Address { get; set; }            
    public required Customer Customer { get; set; }
}

Now when I run the command Add-Migration, I get the following errors:

Unable to create a 'DbContext' of type ''. The exception 'No suitable constructor was found for entity type 'Account. Address#Address'. The following constructors had parameters that could not be bound to Properties of the entity type: Cannot bind 'line1', 'line2', 'city', 'country', or 'postCode' in 'Account.Address#Address(string line1, string line2, string city, string country, string postCode)' Note that only mapped properties can be bound to constructor parameters. Navigations to related entities, including references to owned types, cannot be bound.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,531 Reputation points
    2024-03-07T20:56:16.89+00:00

    I would guess you did not define account/address binding in OnModelCreating()

    0 comments No comments