Search code examples
c#arraysweb-serviceslinq-to-sqlgetjson

How do I return the json data from a multi table?


I am using C# web service + Linq to SQL Classes + Return JSON Data.

For example my table:

table

Data from this table return JSON:

JSON

I want to make this application using C#?


Solution

  • Create New Class for Combine Class:

    public class BadgeVoleModel
    {
        public List<Badge> BadgeList = new List<Badge>();
    
        public List<VoleType> VoleTypeList = new List<VoleType>();
    }
    

    Create Method (return string) for handle get data from DataContext and populate data to BadgeVoleModel, and call from Controller that method.

        public string GetData()
        {
            var data = new Models.BadgeVoleModel();
    
            data.BadgeList = db.Badges.ToList();
            data.VoleTypeList = db.VoleTypes.ToList();
    
            var result = Newtonsoft.Json.JsonConvert.SerializeObject(data);
    
            return result;
        }
    

    And for Deserialize Data:

        public Models.BadgeVoleModel DeserializeData(string data)
        {
            var result = Newtonsoft.Json.JsonConvert
                        .DeserializeObject<Models.BadgeVoleModel>(data);
    
            return result;
        }