City
has list of stores and parks. I want to save store object as json in sql server.
public class City{
public int Id { get; set; }
...
public ICollection<Store> Stores { get; set; }
public ICollection<Park> Parks { get; set; }
public City{
Stores = new List<Store>();
Parks = new List<Park>();
}
}
public class Store{
public int Id { get; set; }
public string Name { get; set; }
}
public class Park{
public int Id { get; set; }
public int CityId { get; set; }
public string Name { get; set; }
}
public class CityConfiguration : IEntityTypeConfiguration<City>
{
public void Configure(EntityTypeBuilder<City> builder)
{
builder.ToTable("Cities");
builder.HasKey(x => x.Id);
builder.Property(e => e.Stores).HasConversion(
v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
v => JsonConvert.DeserializeObject<IList<Store>>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
builder.HasMany(e => e.Parks)
.WithOne(x => x.City)
.HasForeignKey(f => f.CityId);
}
}
When seeding data on test db context I'm populating Store object like this
modelBuilder.Entity<Park>(s =>
{
s.HasData(new Park{ Name = "Park name", CityId = 1, Id = 1 });
});
modelBuilder.Entity<Store>(s =>
{
s.HasData(new Store{ Name = "Store name", Id = 1 });
});
When retriving data
var res = _db.Cities.Where(x => x.Id == id)
.Include(x => x.Parks) // this works fine
.Include(x => x.Stores) // this issues exception
.FirstOrDefault();
System.InvalidOperationException: Lambda expression used inside Include is not valid.
I'm using .net core 3.1.3
Since you're saving the City.Stores
collection as a JSON serialized string, you cannot use it as a navigation collection to child objects. You need to get rid of the .Include(x => x.Stores)
in the query statement:
var res = _db.Cities.Where(x => x.Id == id)
.Include(x => x.Parks) // this works fine
.FirstOrDefault();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.