Ef Core 3.1 value convertor
I have the following code, that uses ef 3.1 core value conversion, I am getting the following error, any idea?
The entity type ‘Address’ requires a primary key to be defined. If you intended to use a keyless entity type call ‘HasNoKey()’.
public class Person { public int Id { get; set; } [Required] [MaxLength(50)] public string FirstName { get; set; } [Required] [MaxLength(50)] public string LastName { get; set; } [Required] public DateTime DateOfBirth { get; set; } public IList<Address> Addresses { get; set; } } public class Address { public string Type { get; set; } public string Company { get; set; } public string Number { get; set; } public string Street { get; set; } public string City { get; set; } }
public class PersonsConfiguration : IEntityTypeConfiguration<Person> { public void Configure(EntityTypeBuilder<Person> builder) { // This Converter will perform the conversion to and from Json to the desired type builder.Property(e => e.Addresses).HasConversion( v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), v => JsonConvert.DeserializeObject<IList<Address>>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); } }
Your address class needs a key. Try adding:
[Key] public int AddressKey { get; set; }
To your address class.