Home > Back-end >  EF Core 5 - Backing field: specified field could not be found for property
EF Core 5 - Backing field: specified field could not be found for property

Time:10-29

I'm trying to create a backing field that consists of a JSON string which is then accessed by a property of the model and converted to a JObject:

public class StaticTable
    {
        public int StaticTableId { get; set; }
        private string _staticData { get; set; }

        public JObject StaticData
        {
            get => JsonConvert.DeserializeObject<JObject>(string.IsNullOrEmpty(_staticData) ? "{}" : _staticData);
            set => _staticData = value.ToString();
        }

        public static void RunFluent(ModelBuilder modelBuilder)
        {
            EntityTypeBuilder<StaticTable> entity = modelBuilder.Entity<StaticTable>();
            entity.Property(s => s.StaticData).HasField("_staticData");
        }
    }

When creating a migration, I receive the following error: System.InvalidOperationException: The specified field '_staticData' could not be found for property 'StaticTable.StaticData'.

Note that RunFluent is executed in DbContext.OnModelCreating

CodePudding user response:

Try a private variable instead of a property

private string _staticData;
  • Related