浪歌 · 随笔 我的开发笔记

efcore8中使用json列

[efcore] 2024/10/24 23:43:23

efcore8开始支持基元集合作为json列存储及查询,sqlserver需要 2016版130版本及以上:

https://learn.microsoft.com/zh-cn/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections

设置参考如下:

modelBuilder
    .Entity<PrimitiveCollections>()
    .Property(e => e.Booleans)
    .HasMaxLength(1024)
    .IsUnicode(false);
efcore7开始支持复杂类型的json列。


设置参考如下:

    单个对象配置:
    

builder.OwnsOne(a => a.MyClass).ToJson(); 
集合对象配置:



builder.OwnsMany(a => a.MyClasses).ToJson(); 



查询json列:

var authorsInChigley = await context.Authors
    .Where(author => author.Contact.Address.City == "Chigley")
    .ToListAsync();


更新json列:


var arthur = await context.Authors.SingleAsync(author => author.Name.StartsWith("Arthur"));

arthur.Contact.Address.Country = "United Kingdom";

await context.SaveChangesAsync();



为JSON列建索引:

 // 为JSON列创建索引
    modelBuilder.Entity<User>()
        .OwnsOne(u => u.Address)
        .ToJson()
        .IndexJsonProperty(a => a.City);

    // 对集合进行索引
    modelBuilder.Entity<User>()
        .OwnsMany(u => u.PhoneInfos)
        .ToJson()
        .IndexJsonProperty(p => p.Type);