How to store JSON in an entity field with EF Core?

前端 未结 10 484
死守一世寂寞
死守一世寂寞 2020-11-29 17:13

I am creating a reusable library using .NET Core (targeting .NETStandard 1.4) and I am using Entity Framework Core (and new to both). I have an entity class that looks like

10条回答
  •  [愿得一人]
    2020-11-29 18:19

    Going to answer this one differently.

    Ideally the domain model should have no idea how data is stored. Adding backing fields and extra [NotMapped] properties is actually coupling your domain model to your infrastructure.

    Remember - your domain is king, and not the database. The database is just being used to store parts of your domain.

    Instead you can use EF Core's HasConversion() method on the EntityTypeBuilder object to convert between your type and JSON.

    Given these 2 domain models:

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

    I have only added attributes that the domain is interested in - and not details that the DB would be interested in; I.E there is no [Key].

    My DbContext has the following IEntityTypeConfiguration for the Person:

    public class PersonsConfiguration : IEntityTypeConfiguration
    {
        public void Configure(EntityTypeBuilder 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>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
        }
    }
    

    With this method you can completely decouple your domain from your infrastructure. No need for all the backing field & extra properties.

提交回复
热议问题