How to save nested JSON into SQL Server using C# on .NET Core with Entity Framework?

I have my JSON objects in this format:

[
    {
        "id": "k002f3d",        
        "usage": {
            "sent": 0,
            "recv": 2,
            "total": 2
        }
    },
    {
        "id": "k641327",        
        "usage": {
            "sent": 0,
            "recv": 2,
            "total": 2
        }
    },
    {
        "id": "k6419b2",        
        "usage": {
            "sent": 872,
            "recv": 5912,
            "total": 6784
        }
    }
]

I would like to save it into a SQL Server table. I have defined my table to store that information like this:

And this is my POCO class in C#:

This is the way I initialize POCO object:

newClient is an object that we modify some property before adding to SQL Server database. When db.SaveChanges() is executed, it raises an error of not defined relationship between object or need use [NotMapped] attribute before property. As you can see, Usage is just a subset of property of the object itself.

Would you mind to guide me how can I do to be able to save record to database? I have tried to put [NotMapped] attribute before property usage in the class Log definition, error not generated but no data save for sent, recv, and total property of object Usage.

2

First of all, you need primary keys in both the Log and Usage entities to uniquely identify records in each table. Then, you need to define the relationship between the Log and Usage entities in Entity Framework. This involves setting up navigation properties and foreign keys to establish the connection between the Log and Usage tables in your database. Michał Turczyn wrote how to implement this in your Code in the Answer above.

If you use auto-increment on the primary key, you only need to add or update your Log entity in the database context. However, this will not automatically create a related Usage entity unless the Usage entity is properly instantiated and added to the context as well.

To deserialize your JSON into a Log object, you can use the Newtonsoft.Json NuGet package. Ensure that the JSON structure matches the Log class, including any nested objects for related entities. Then, you can deserialize it directly into the class without needing complex code.

If you want to retrieve a Log from your database along with its related Usage, you need to use the Include method to eagerly load the related data. Here’s an example of how to do that:

var logWithUsage = context.Log
.Include(log => log.Usage)
.FirstOrDefault(log => log.Id == someLogId);

This will load the Log entity with its associated Usage entity in a single query, ensuring that both entities are available when needed. Remember, eager loading with Include is crucial if you want to access related data without making separate database calls for each entity.

You should define foreign key relation:

public class Usage
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public int? sent { get; set; }

    public int? recv { get; set; }

    public int? total { get; set; }
}

Add also usageId property in Log entity:

public class Log
{
    public string id { get; set; }
    public int usageId { get; set; }
    public Usage usage { get; set; }
}

and then your code should work out of the box, as all the IDs should be now assigned automatically.

UPDATE

You also can define one table (one entity), like so:

public class Log
{
    public string id { get; set; }

    public int? sent { get; set; }

    public int? recv { get; set; }

    public int? total { get; set; }
}

And then treat your JSON as DTOs, so you need to define classes for DTOs:

public class UsageDto
{
    public int? sent { get; set; }

    public int? recv { get; set; }

    public int? total { get; set; }
}
public class LogDto
{
    public string id { get; set; }
    public UsageDto usage { get; set; }
}

Then you need to adjust your code, so it does the appropriate mapping:

var rawJson = @"[
    {
        ""id"": ""k002f3d"",        
        ""usage"": {
            ""sent"": 0,
            ""recv"": 2,
            ""total"": 2
        }
    },
    {
        ""id"": ""k641327"",        
        ""usage"": {
            ""sent"": 0,
            ""recv"": 2,
            ""total"": 2
        }
    },
    {
        ""id"": ""k6419b2"",        
        ""usage"": {
            ""sent"": 872,
            ""recv"": 5912,
            ""total"": 6784
        }
    }
]";

var dtos = JsonSerializer.Deserialize<LogDto[]>(rawJson);

var logs = dtos
    .Select(x => new Log
    {
        id = x.id,
        sent = x.usage.sent,
        recv = x.usage.recv,
        total = x.usage.total,
    }).ToArray();

6

Save nested JSON data into SQL Server using Entity Framework Core by defining model classes that represent the JSON structure, configuring relationships in the DbContext, and deserializing the JSON before saving it to the database.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật