City
有商店和公园的清单。我想在SQL Server中将存储对象另存为json。
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);
}
}
当在测试数据库上下文中播种数据时,我正在像这样填充Store对象
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 });
});
检索数据时
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:在Include中使用的Lambda表达式无效。
我正在使用.net core 3.1.3
由于您将City.Stores
集合另存为JSON序列化字符串,因此无法将其用作子对象的导航集合。您需要摆脱.Include(x => x.Stores)
查询语句中的:
var res = _db.Cities.Where(x => x.Id == id)
.Include(x => x.Parks) // this works fine
.FirstOrDefault();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句