简体   繁体   English

在 EF Core 3 中映射 json

[英]Mapping json in EF Core 3

City has list of stores and parks. City有商店和公园的清单。 I want to save store object as json in sql server.我想在 sql 服务器中将存储 object 保存为 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);
    }
}

When seeding data on test db context I'm populating Store object like this在测试数据库上下文中播种数据时,我正在像这样填充存储 object

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. System.InvalidOperationException:包含内使用的 Lambda 表达式无效。

I'm using .net core 3.1.3我正在使用 .net 核心 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.由于您将City.Stores集合保存为 JSON 序列化字符串,因此您不能将其用作子对象的导航集合。 You need to get rid of the .Include(x => x.Stores) in the query statement:您需要删除查询语句中的.Include(x => x.Stores)

var res = _db.Cities.Where(x => x.Id == id)
                .Include(x => x.Parks)  // this works fine           
                .FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM