0

I wan't to add to my ApplicationUser class, which derives from the Microsoft.AspNetCore.Identity.IdentityUser class an custom property but not as string nor Id but as a custom object. This object is not part of the database, it comes from a different Api (and therefore from a different database). Is there a way to customize the serialization/deserialization for example with JSON so that the object will be saved as JSON string in the database? Or is there another way to save user defined classes/objects in the database?

public class ApplicationUser : IdentityUser
{
    public ExternalApi.OrganizationItem Organization { get; set; }

    [ForeignSerialization("Organization")]//this does not exist, but is there something like this?
    public string OrganizationJson { get; set; }    
}

Edit: I wrote a workaround myself but I still wonder if there is any built-in solution in EF-Core for this problem.

public class ApplicationUser : IdentityUser
{
    private OrganizationListItem? _organization;
    public Api.OrganizationListItem? Organization
    {
        get => _organization ??= (OrganizationJson == null ? null : JsonSerializer.Deserialize<Api.OrganizationListItem>(OrganizationJson));
        set
        {
            OrganizationJson = value == null ? null : JsonSerializer.Serialize(value);
            _organization = value;
        }
    }
    public string? OrganizationJson { get; set; }
}

... and in DbContext:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.Entity<ApplicationUser>().Ignore(c => c.Organization);
}
Max R.
  • 811
  • 1
  • 13
  • 31

0 Answers0