Home > Net >  Backing different prop type in .NET, EF with C#
Backing different prop type in .NET, EF with C#

Time:02-01

I tried to do the following:

Product model:

public class Product : BaseEntity
{
    public string Name { get; set; }
    public string Description { get; set; }
    private string _PictureUrls;

    [NotMapped]
    public string[] PictureUrls
    {
        get { return _PictureUrls.Split(','); }
        set { _PictureUrls = string.Join(',', value); }
    }
}

and:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder
      .Entity<Product>()
      .Property(props => props.PictureUrls)
      .HasField("_PictureUrls")
      .UsePropertyAccessMode(PropertyAccessMode.PreferFieldDuringConstruction);
}

I keep getting the error:

The specified field '_PictureUrls' of type 'string' cannot be used for the property 'Product.PictureUrls' of type 'string[]'. Only backing fields of types that are compatible with the property type can be used.

I understand why, but can't figure out how to solve this, help please.

CodePudding user response:

Do consider making PictureUrl an entity, but what you're attempting will work.

The string needs to be a shadow property of string type, not mapped to the array property. eg

    modelBuilder.Entity<Product>()
                .Property(typeof(string), "_PictureUrls")
                .HasField("_PictureUrls")
                .HasColumnName("PictureUrls")
                .UsePropertyAccessMode(PropertyAccessMode.PreferFieldDuringConstruction);
  • Related