Home > Enterprise >  .NET EF Core - The specified field could not be found for property
.NET EF Core - The specified field could not be found for property

Time:01-27

I'm trying make a migration in .NET EF Core but still getting error:

The specified field '_tags' could not be found for property Document<FinancialReport>.Tags

I need to save string array (tags) as one string separated by comma to the database. I found exactly what I need (https://kimsereyblog.blogspot.com/2017/12/save-array-of-string-entityframework.html), but when I try to make migration I got the error.

My main class in which I need to do that looks this:

public class DocumentBase<T>
{
    private string? _tags { get; set; }

    public int Id { get; set; }

    [NotMapped]
    public string[] Tags
    {
        get { return _tags?.Split(',') ?? Array.Empty<string>(); }
        set { _tags = value?.ToArray().Any() ?? false ? string.Join(",", value.ToArray()) : null; }
    }

    public T? Data { get; set; }
}

And then I setting _tags property as backing field in overridden method OnModelCreating() in dataContext:

public class DataContext : DbContext
{
    public DbSet<Document<FinancialReport>> FinancialReports { get; set; }

    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Document<FinancialReport>>()
            .Property(p => p.Tags)
            .HasField("_tags");
    }
}

I tried use BackingField attribute for Tags property, make _tags a field (remove getter & setter) instead of property, but it also didn't help. Any ideas what am I missing?

CodePudding user response:

When using formatted properties like this, I will used a mapped property for the raw data value then a [NotMapped] formatted value:

    [Column("Tags")]
    public string? TagsValue { get; set; }

    [NotMapped]
    public string[] Tags
    {
        get { return TagsValue?.Split(',') ?? Array.Empty<string>(); }
        set { TagsValue = value?.ToArray().Any() ?? false ? string.Join(",", value.ToArray()) : null; }
    }

The do away with the extra OnModelCreating configuration.

The care needed with [NotMapped] fields is to ensure they don't end up in any Linq expressions that would go to SQL.

  • Related