【发布时间】:2020-05-15 17:18:45
【问题描述】:
City 有商店和公园的列表。
我想在 sql server 中将 store 对象保存为 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 : 内部使用的 Lambda 表达式 包含无效。
我正在使用 .net core 3.1.3
【问题讨论】:
标签: c# .net entity-framework .net-core