nix
nix

Reputation: 2285

Is there a way to map complex type to the string?

Is there a way to map complex type to the string?

I'm doing custom mapping like following:

foreach (var pb in modelBuilder.Model
            .GetEntityTypes()
            .SelectMany(t => t.GetProperties())
            .Where(p => p.ClrType == typeof(SomeComplexType) && !Attribute.IsDefined(p.GetMemberInfo(false, false), typeof(Padding)))
            .Select(p => modelBuilder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name)))
        {
            pb.HasConversion(new ValueConverter<SomeComplexType, string>(
                v => v.ToString(),
                v => SomeComplexType.Parse(v)));
        }

But when running migrations I get

The property 'SomeEntity.ComplexTypeProperty' could not be mapped, because it is of type 'SomeComplexType' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

So I want to be able to map complex type to string and save it as such.

Upvotes: 1

Views: 415

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239200

Your best bet is to JSON encode it:

pb.HasConversion(new ValueConverter<SomeComplexType, string>(
    v => JsonConvert.SerializeObject(v),
    v => JsonConvert.DeserializeObject<SomeComplexType>(v)));

In ASP.NET Core 3.0, you'd use System.Text.Json instead, so the methods would be JsonSerializer.ToString(v) and JsonSerializer.Parse<SomeComplexType>(v)

Upvotes: 1

Related Questions