Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

How to create a json from database using linq

I am new in linq query. I have got a task to create a json from db datas using linq query. My db is DB data

Here i want to create a json like the below format

        {
            "label": "Invoices",
            "items": [
                {
                    "label": "Valpara_Jan",
                    "items": [
                        {
                            "label": "Estate1_Jan"
                        },
                        {
                            "label": "Estate2_Jan"
                        }
                    ]
                },
                {
                    "label": "Munnar_Jan"
                }
            ]
        }

How can I create the json? The data should based on the parent id. For eg: Valpara and Munnar must come under invoice. Please help

Upvotes: 0

Views: 60

Answers (2)

Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

public JsonResult FolderList()
        {
            IEnumerable<LabelMaster> folders = db.LabelMaster.Where(x => x.UserId == AppSession.User.UserID || (x.UserId == 0 && x.ParentLabelId != 0)).AsEnumerable();                   
            var foldernodes = (folders.RecursiveJoin(element => element.LabelId,
            element => element.ParentLabelId,
            (LabelMaster element, IEnumerable<folder> children) => new folder()
            {
                labelId = element.LabelId,
                label= element.LabelName,
                parentId= element.ParentLabelId,
                userId= element.UserId,
                active = element.Active,
                items = children
            })).ToList();
            return Json(foldernodes, JsonRequestBehavior.AllowGet);
        }

Upvotes: 0

mby
mby

Reputation: 91

you use entity framework or linq2sql? and mvc? if that true, than you can use Json method of your Controller. smth like this

List<MyTypeDbTable>data=GetDataFromDb();
JsonResult res=Json(data);
string json = new JavaScriptSerializer().Serialize(res.Data);

Upvotes: 1

Related Questions