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

58 Views Asked by At

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; }        
}

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

1

There are 1 best solutions below

1
stemixrf On

Is this the issue, "Note that only mapped properties can be bound to constructor parameters"

from the docs at .. Entity types with constructors

Read-only properties

Once properties are being set via the constructor it can make sense to make some of them read-only. EF Core supports this, but there are some things to look out for:

Properties without setters are not mapped by convention. (Doing so tends to map properties that should not be mapped, such as computed properties.) Using automatically generated key values requires a key property that is read-write, since the key value needs to be set by the key generator when inserting new entities.

An easy way to avoid these things is to use private setters

EF Core sees a property with a private setter as read-write, which means that all properties are mapped as before and the key can still be store-generated.