foreign key issues in GET METHOD in web api - c#

i have a table users which have a column with foreign key... when i post a request in postman of get or get by id it shows the foreign key table data also. i want to show only "USERS" table data only.
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Taylor.Models;
namespace Taylor.API_Controller
{
[RoutePrefix("api/Suit")]
public class SuitController : ApiController
{
public TaylorEntities db = new TaylorEntities();
// GET api/<controller>
public List<Suit> GetAllSuit()
{
return db.Suit.ToList();
}
here is a class
namespace Taylor.Models
{
using System;
using System.Collections.Generic;
public partial class Users
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Users()
{
this.AppUser = new HashSet<AppUser>();
}
public int UserId { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public int UserRoleId { get; set; }
public bool IsActive { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public int CreatedBy { get; set; }
public Nullable<System.DateTime> ModifiedAt { get; set; }
public int ModifiedBy { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AppUser> AppUser { get; set; }
public virtual UserRole UserRole { get; set; }
}
}
in POSTMAN when i request a GET METHOD https://localhost:44311/api/User/6
it shows this much data
{
"$id": "1",
"AppUser": [],
"UserRole": {
"$id": "2",
"Users": [
{
"$ref": "1"
},
{
"$id": "3",
"AppUser": [
{
"$id": "4",
"Location": {
"$id": "5",
"AppUser": [
{
"$ref": "4"
},
{
"$id": "6",
"Location": {
"$ref": "5"
},
"Users": {
"$ref": "3"
},
"Customer": [],
"AppUserId": 4,
"AdminUserId": 1,
"StartDate": "2021-07-26T04:18:42.893",
"EndDate": "2021-07-26T04:18:42.893",
"LocationId": 1,
"City": "Lahore",
"RegisterDate": "2021-07-26T04:18:42.893",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "7",
"Location": {
"$ref": "5"
},
"Users": {
"$ref": "3"
},
"Customer": [],
"AppUserId": 5,
"AdminUserId": 1,
"StartDate": "2021-07-26T04:18:42.893",
"EndDate": "2021-07-26T04:18:42.893",
"LocationId": 1,
"City": "Islamabad",
"RegisterDate": "2021-07-26T04:18:42.893",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "8",
"Location": {
"$ref": "5"
},
"Users": {
"$id": "9",
"AppUser": [
{
"$ref": "8"
}
],
"UserRole": {
"$ref": "2"
},
"UserId": 3,
"Name": "Haider",
"PhoneNumber": "0347-8526942",
"Email": "haider#yahoo.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
"Customer": [
{
"$id": "10",
"AppUser": {
"$ref": "8"
},
"Nap": [
{
"$id": "11",
"Customer": {
"$ref": "10"
},
"NapDetails": [
{
"$id": "12",
"Nap": {
"$ref": "11"
},
"Suit": {
"$id": "13",
"NapDetails": [
{
"$ref": "12"
}
],
"SuitId": 1,
"Title": "Pent",
"IsActive": true,
"CreatedAt": "2021-07-25T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-25T00:00:00",
"ModifiedBy": 1
},
"NapDetailsId": 1,
"SuitId": 1,
"Measurement": "62,25,2514",
"NapId": 1,
"IsActive": true,
"CreatedAt": "2021-07-29T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-29T00:00:00",
"ModifiedBy": 1
},
{
"$id": "14",
"Nap": {
"$ref": "11"
},
"Suit": {
"$id": "15",
"NapDetails": [
{
"$ref": "14"
}
],
"SuitId": 2,
"Title": "Shirt",
"IsActive": true,
"CreatedAt": "2021-07-25T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-25T00:00:00",
"ModifiedBy": 1
},
"NapDetailsId": 2,
"SuitId": 2,
"Measurement": "fbsh,2514785",
"NapId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"NapId": 1,
"CustomerId": 1,
"ImageUrl": "sgjakdvaksgfew",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "16",
"Customer": {
"$ref": "10"
},
"NapDetails": [],
"NapId": 4,
"CustomerId": 1,
"ImageUrl": "sgjakdvaksgfew",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"CustomerId": 1,
"AppUserId": 3,
"PhoneNumber": "0321-8521475",
"CustomerName": "Talha",
"Address": "Multan",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "17",
"AppUser": {
"$ref": "8"
},
"Nap": [],
"CustomerId": 3,
"AppUserId": 3,
"PhoneNumber": "0321-8521475",
"CustomerName": "Abu Bakar",
"Address": "Multan",
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"AppUserId": 3,
"AdminUserId": 3,
"StartDate": "2021-07-26T00:00:00",
"EndDate": "2021-07-31T00:00:00",
"LocationId": 1,
"City": "karachi",
"RegisterDate": "2001-12-15T00:00:00",
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
}
],
"Location1": {
"$ref": "5"
},
"Location2": {
"$ref": "5"
},
"LocationId": 1,
"Lat": 0.254,
"Long": 0.568,
"IsActive": true,
"CreatedAt": "2021-07-15T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-15T00:00:00",
"ModifiedBy": 1
},
"Users": {
"$ref": "3"
},
"Customer": [],
"AppUserId": 1,
"AdminUserId": 1,
"StartDate": "2021-06-15T00:00:00",
"EndDate": "2021-07-15T00:00:00",
"LocationId": 1,
"City": "multan",
"RegisterDate": "2001-06-24T00:00:00",
"IsActive": true,
"CreatedAt": "2021-07-15T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-15T00:00:00",
"ModifiedBy": 1
},
{
"$ref": "6"
},
{
"$ref": "7"
}
],
"UserRole": {
"$ref": "2"
},
"UserId": 1,
"Name": "Khakan",
"PhoneNumber": "0300-1234567",
"Email": "khakan#gmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
},
{
"$ref": "9"
},
{
"$id": "18",
"AppUser": [],
"UserRole": {
"$ref": "2"
},
"UserId": 4,
"Name": "Shahzad",
"PhoneNumber": "0347-8526942",
"Email": "shahzad#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
},
{
"$id": "19",
"AppUser": [],
"UserRole": {
"$ref": "2"
},
"UserId": 7,
"Name": "Mr. Johny",
"PhoneNumber": "0300-6589321",
"Email": "johny#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
},
{
"$id": "20",
"AppUser": [],
"UserRole": {
"$ref": "2"
},
"UserId": 8,
"Name": "Usman Khan",
"PhoneNumber": "0321-9632584",
"Email": "usman#gmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
],
"UserRoleId": 1,
"Title": "Admin",
"IsActive": true,
"CreatedAt": "2021-07-26T00:00:00",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T00:00:00",
"ModifiedBy": 1
},
"UserId": 6,
"Name": "Awais",
"PhoneNumber": "0321-9632584",
"Email": "awais#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}
but i want only this one
"UserId": 6,
"Name": "Awais",
"PhoneNumber": "0321-9632584",
"Email": "awais#hotmail.com",
"UserRoleId": 1,
"IsActive": true,
"CreatedAt": "2021-07-26T04:18:42.893",
"CreatedBy": 1,
"ModifiedAt": "2021-07-26T04:18:42.893",
"ModifiedBy": 1
}

You need to give more information on what framework you are using on the backend side to interact with the database.
If entity framework has been used, probably the query to get the result from the database has "Include" extension method, that's why it is fetching the foreign data too.

You can create new User like this for given Id
var user = conetxt.Users
.Select(u=> new User{ UserId = u.UserId, UserName = u.UserName, ... })
.SingleOrDefault(u=>u.UserId == id);
If you want have List<User>
var user = conetxt.Users
.Select(u=> new User{ UserId = u.UserId, UserName = u.UserName, ... })
.ToList();
It is suggested to use
DTO
instead of Model for Response You should expose only required properties to the client

Related

Accessing JSON value from nested list in C#

I am trying to loop through some JSON to create some variables using a dictionary.
Here are the definitions that I am using:
public class Customfield10002
{
public string name { get; set; }
}
public class Fields
{
public string summary { get; set; }
public List<Customfield10002> customfield_10002 { get; set; }
}
public class Issue
{
public string id { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Root
{
public List<Issue> issues { get; set; }
}
The following code validates fine.
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(response.Content);
foreach (var issue in myDeserializedClass.issues)
{
string id = issue.id.ToString();
string key = issue.key.ToString();
string summary = issue.fields.summary.ToString();
{
But when I include the following string field, it fails validation
string creatoremail = issue.fields.customfield_10002.name.ToString();
The error is:
'List<ITSDWorklogs.Customfield10002' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type"
'List<ITSDWorklogs.Customfield10002' could be found (are you missing a using directive or an assembly reference?)
How can I access the value from this nested list?
Any help greatly appreciated.
UPDATED with JSON
{
"expand": "names,schema",
"startAt": 0,
"maxResults": 1,
"total": 151,
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id": "10210",
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issue/10210",
"key": "ITSD-202",
"fields": {
"statuscategorychangedate": "2021-01-25T20:12:11.922+0000",
"issuetype": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issuetype/10003",
"id": "10003",
"description": "For customer support issues. Created by Jira Service Desk.",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/secure/viewavatar?size=medium&avatarId=10308&avatarType=issuetype",
"name": "Support",
"subtask": false,
"avatarId": 10308
},
"timespent": null,
"customfield_10030": null,
"customfield_10031": {
"id": "1",
"name": "Time to resolution",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/request/10210/sla/1"
},
"completedCycles": [],
"ongoingCycle": {
"startTime": {
"iso8601": "2021-01-25T20:12:11+0000",
"jira": "2021-01-25T20:12:11.592+0000",
"friendly": "Yesterday 08:12",
"epochMillis": 1611605531592
},
"breachTime": {
"iso8601": "2021-02-11T14:30:00+0000",
"jira": "2021-02-11T14:30:00.000+0000",
"friendly": "11/Feb/21 02:30",
"epochMillis": 1613053800000
},
"breached": false,
"paused": false,
"withinCalendarHours": false,
"goalDuration": {
"millis": 432000000,
"friendly": "120h"
},
"elapsedTime": {
"millis": 0,
"friendly": "0m"
},
"remainingTime": {
"millis": 432000000,
"friendly": "120h"
}
}
},
"project": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/project/10000",
"id": "10000",
"key": "ITSD",
"name": "Customer Service Desk",
"projectTypeKey": "service_desk",
"simplified": false,
"avatarUrls": {
"48x48": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?pid=10000&avatarId=10412",
"24x24": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=small&s=small&pid=10000&avatarId=10412",
"16x16": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=xsmall&s=xsmall&pid=10000&avatarId=10412",
"32x32": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=medium&s=medium&pid=10000&avatarId=10412"
}
},
"customfield_10032": {
"id": "2",
"name": "Time to first response",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/request/10210/sla/2"
},
"completedCycles": [],
"ongoingCycle": {
"startTime": {
"iso8601": "2021-01-25T20:12:11+0000",
"jira": "2021-01-25T20:12:11.592+0000",
"friendly": "Yesterday 08:12",
"epochMillis": 1611605531592
},
"breachTime": {
"iso8601": "2021-01-26T12:30:00+0000",
"jira": "2021-01-26T12:30:00.000+0000",
"friendly": "Today 12:30",
"epochMillis": 1611664200000
},
"breached": false,
"paused": false,
"withinCalendarHours": false,
"goalDuration": {
"millis": 14400000,
"friendly": "4h"
},
"elapsedTime": {
"millis": 0,
"friendly": "0m"
},
"remainingTime": {
"millis": 14400000,
"friendly": "4h"
}
}
},
"fixVersions": [],
"customfield_10034": {
"languageCode": "en",
"displayName": "English"
},
"resolution": null,
"customfield_10037": null,
"customfield_10027": null,
"customfield_10028": null,
"customfield_10029": null,
"resolutiondate": null,
"workratio": -1,
"lastViewed": "2021-01-25T20:12:11.936+0000",
"watches": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issue/ITSD-202/watchers",
"watchCount": 1,
"isWatching": true
},
"created": "2021-01-25T20:12:11.592+0000",
"customfield_10020": null,
"customfield_10021": null,
"customfield_10022": null,
"customfield_10023": null,
"priority": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/priority/3",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/images/icons/priorities/medium.svg",
"name": "Medium",
"id": "3"
},
"customfield_10024": null,
"customfield_10025": null,
"labels": [],
"customfield_10026": [],
"customfield_10016": null,
"customfield_10017": null,
"customfield_10018": {
"hasEpicLinkFieldDependency": false,
"showField": false,
"nonEditableReason": {
"reason": "PLUGIN_LICENSE_ERROR",
"message": "The Parent Link is only available to Jira Premium users."
}
},
"customfield_10019": "0|i0013b:",
"timeestimate": null,
"versions": [],
"assignee": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"updated": "2021-01-25T20:12:14.321+0000",
"status": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/status/10001",
"description": "This was auto-generated by Jira Service Desk during workflow import",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/images/icons/status_generic.gif",
"name": "Waiting for support",
"id": "10001",
"statusCategory": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/statuscategory/4",
"id": 4,
"key": "indeterminate",
"colorName": "yellow",
"name": "In Progress"
}
},
"components": [],
"customfield_10050": null,
"customfield_10051": null,
"timeoriginalestimate": null,
"customfield_10052": null,
"customfield_10053": null,
"description": null,
"customfield_10010": null,
"customfield_10014": null,
"customfield_10015": null,
"customfield_10005": null,
"customfield_10049": null,
"customfield_10006": null,
"customfield_10007": null,
"security": null,
"customfield_10008": null,
"customfield_10009": null,
"summary": "Barry Test",
"creator": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"customfield_10040": null,
"customfield_10041": null,
"customfield_10042": null,
"customfield_10043": null,
"reporter": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"customfield_10044": null,
"customfield_10000": "{}",
"customfield_10001": null,
"customfield_10045": null,
"customfield_10046": null,
"customfield_10002": [
{
"id": "4",
"name": "xxxxxxxxxx.co.uk",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/organization/4"
}
}
],
"customfield_10003": null,
"customfield_10047": null,
"customfield_10048": null,
"customfield_10004": null,
"customfield_10038": null,
"customfield_10039": null,
"environment": null,
"duedate": null,
"progress": {
"progress": 0,
"total": 0
}
}
}
]
}
you can use LINQ for enumerate over Customfield10002 list:
var createOrEmail = issue.fields.customfield_10002.Select(c=>c.name).DefaultIfEmpty("").Aggregate((s, s1) => $"{s}, {s1}");
This should work as suggested by #gunr2171
string creatoremail = "";
foreach (var names in issue.fields.customfield_10002)
{
creatoremail = names.name.ToString();
}
or by Sajid
string creatoremail = issue.fields.customfield_10002.FirstOrDefault().name.ToString();
Regards

How to assign same Json property name, one having value and other being null?

In the json response the property "data" is used as a List and in other places in the Json it is used as a string.. when its used in the List the property has some value when its using as a string the value is coming as null..
How to include both scenario here when I am deserialzing and serializing the json.. without running in to exception A member with the name 'data' already exists. Use the JsonPropertyAttribute to specify another name
public class Example
{
[JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
public List<Datum> Data { get; set; }
[JsonProperty("data", NullValueHandling = NullValueHandling.Include)]
public string Data { get; set; }
}
Here is what I tried to use a private property but not able to resolve the issue
[JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
public List<Datum> Data { get; set; }
[JsonProperty("data2", NullValueHandling = NullValueHandling.Include)]
private List<Datum> Data2 { set { Data = value; } }
Here is the Json
{
"adRoots": null,
"allowedTagTypes": [
0,
1,
4
],
"canEdit": true,
"filterConfigData": {
"config": [{
"extraData": null,
"id": "Endpoints.ID.SearchInProgress",
"title": "Search in Progress",
"type": 5
},
{
"data": null,
"extraData": null,
"id": "Endpoints.ID.Policies",
"source": {
"definition": "dbo",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "Policies",
"type": 1
},
"title": "Policies",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.ID.MACs",
"title": "MAC Addresses",
"type": 1
},
{
"data": [{
"name": "Endpoint Closed",
"value": 11
},
{
"name": "Endpoint Completed",
"value": 15
},
{
"name": "Endpoint Opened",
"value": 10
}
],
"extraData": null,
"id": "Endpoints.ID.ClientActivityState",
"source": {
"definition": "State",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "ClientActivityState",
"type": 2
},
"title": "Client Activity State",
"type": 3
},
{
"data": [{
"name": "System Alarm",
"value": 3
},
{
"name": "System Audit",
"value": 2
}
],
"extraData": null,
"id": "Endpoints.ID.AceType",
"source": {
"definition": "AceType",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "AceType",
"type": 2
},
"title": "ACL: ACE Type",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.ID.AceWho",
"title": "ACL: Trustee",
"type": 1
},
{
"data": [{
"name": "Append Data",
"value": 4
},
{
"name": "Delete",
"value": 65536
},
{
"name": "Execute",
"value": 32
}
],
"extraData": null,
"id": "Endpoints.ID.AceRights",
"source": {
"definition": "AceRights",
"displayColumn": "Name",
"editor": "ViewModel",
"keyColumn": "Id",
"name": "AceRights",
"type": 2
},
"title": "ACL: Authorization",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.ID.FilterTagName",
"title": "Tag Name",
"type": 1
},
{
"data": null,
"extraData": null,
"id": "Endpoints.ID.FilterTags",
"source": {
"definition": "dbo",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "Tags",
"type": 1
},
"title": "Tags",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.Name.EndpointName",
"title": "Endpoint Name",
"type": 1
},
{
"data": null,
"extraData": null,
"id": "Endpoints.Version.Version",
"title": "Endpoint Version",
"type": 1
},
{
"extraData": null,
"id": "Endpoints.Platform.Platform",
"title": "Endpoint Platform",
"type": 1
},
{
"data": [{
"name": "Desktop",
"value": 1
},
{
"name": "Server",
"value": 2
},
{
"name": "Unknown",
"value": 0
}
],
"extraData": null,
"id": "ELPlatformType",
"source": {
"displayColumn": "Name",
"keyColumn": "Id",
"name": "PlatformType",
"type": 2
},
"title": "Platform Type",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.LastPoll.LastPoll",
"title": "Last Poll Time",
"type": 2
}
],
"pagedListItems": null
},
"forests": null,
"item": {
"disallowed": false,
"editPermissions": 0,
"endpointsCount": 0,
"filter": null,
"id": 404,
"ldapPaths": null,
"name": "tag",
"query": null,
"type": 0
}
}

Entity Framework Core Parent/Child Clean query with multi level child [duplicate]

This question already has an answer here:
Map category parent id self referencing table structure to EF Core entity
(1 answer)
Closed 2 years ago.
I have an issue on cleaning querying my parent child without repeating the children at its own root of the list.
Object
public class Office
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public bool Inactive { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public Office Parent { get; set; }
[InverseProperty("Parent")]
public virtual ICollection<Office> Children { get; set; }
}
}
The Query
public async Task<IEnumerable<Office>> GetOffices()
{
return await _context.Offices.Where(os => !os.Inactive)
.Include(o => o.Parent)
.Include(o => o.Children).ToListAsync();
}
And the result
{
"id": 5,
"name": "AA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"parent": {
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
"children": [
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"children": []
}
]
},
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"parent": {
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"parent": {
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
"children": []
},
"children": []
},
,
{
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": [
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"children": [
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"children": []
}
]
}
]
}
This also has child objects at the root level so I tried this
public async Task<IEnumerable<Office>> GetOffices()
{
return await _context.Offices.Where(os => !os.Inactive && !os.ParentId.HasValue).Include(o => o.Parent).Include(o => o.Children).ToListAsync();
}
And this is the result of the other query
{
"id": 5,
"name": "AA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
{
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": [
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"children": null
}
]
}
This leaves out id 1010 BAAA child object. Idealy I would like to have it come out as
{
"id": 5,
"name": "AA",
"inactive": false,
"parentId": null,
"parent": null,
"children": []
},
{
"id": 2,
"name": "BA",
"inactive": false,
"parentId": null,
"parent": null,
"children": [
{
"id": 10,
"name": "BAA",
"inactive": false,
"parentId": 2,
"children": [
{
"id": 1011,
"name": "BAAA",
"inactive": false,
"parentId": 10,
"children": []
}
]
}
]
}
No matter how I stack the query I can't seem to get this to display this way. Is there a way to adjust the query to allow this or an easy post query command to trim only the root level objects that are a child?
If you want limited number of child levels (2 in this example) fetched you can try:
await _context.Offices
.Where(os => !os.Inactive && !os.ParentId.HasValue)
.Include(o => o.Parent)
.Include(o => o.Children)
.ThenInclude(o => o.Children)
.ToListAsync()

how to convert json code to getset property

i have following code any one tell me how to convert this in class automatically .its very hard to convert code..please help me
[{
"karhoo_ref": "4325226970648863",
"supplier_company": "supplier1",
"booking_id": "32434234234",
"notes": "waited at southeast corner",
"status": "completed",
"vehicle": {
"vehicle_type": "suv",
"vehicle_id": "404",
"vehicle_plate": "BD51SMR",
"latitude": 40.73892,
"longitude": -73.9873663,
"eta_minutes": null,
"make": "Cadillac",
"model": "Escalade",
"color": "Black",
"eta_minutes": null,
"driver_id": "12121",
"driver_phone": "+14157854978",
"driver_first_name": "Sam",
"driver_last_name": "Smith",
"direction": {
"kph": 20,
"heading": 90
}
},
"total": 29.10,
"currency": "USD"
"price_components": [{
"component_name": "base rate",
"value": 27.10,
"description": "Base Rate"
}, {
"component_name": "parking",
"value": 0,
"description": "Parking"
}, {
"component_name": "tolls",
"value": 0,
"description": "Tolls"
}, {
"component_name": "meet greet",
"value": 0,
"description": "Meet & Greet",
"currency": "USD"
}, {
"component_name": "stop charges",
"value": 0,
"description": "Stop Charges"
}, {
"component_name": "wait time charges",
"value": 0,
"description": "Wait Time charges"
}, {
"component_name": "discount",
"value": 0,
"description": "Discount"
}, {
"component_name": "misc fee",
"value": 0,
"description": "Misc"
}, {
"component_name": "fuel surcharge",
"value": 0,
"description": "Fuel Surcharge"
}, {
"component_name": "service charge",
"value": 0,
"description": "Service Charge"
}, {
"component_name": "gratuity",
"value": 0,
"description": "Tips"
}, {
"component_name": "workers comp tax",
"value": 0,
"description": "NYC Workers Comp Tax"
}, {
"component_name": "tax",
"value": 2.00,
"description": "8.75% State"
}]
}, {
"karhoo_ref": "2825226970648863",
"supplier_company": "supplier2",
"booking_id": "ABC2155",
"notes": "waited at southeast corner",
"status": "completed",
"vehicle": {
"vehicle_type": "sedan",
"vehicle_id": "404",
"vehicle_plate": "BD51SMR",
"latitude": 40.73892,
"longitude": -73.9873663,
"eta_minutes": null,
"make": "Toyota",
"model": "Camery",
"color": "Black",
"driver_id": "12121",
"driver_phone": "4157854978",
"driver_first_name": "Sam",
"driver_last_name": "Smith",
"direction": {
"kph": 20,
"heading": 90
}
},
"total": 27.10,
"currency": "USD"
"price_components": [{
"component_name": "base rate",
"value": 27.10,
"description": "Base Rate"
}]
}]
i want like this.
public class ToLocation
{
public ToLocation()
{
address = new Address2();
}
public double latitude { get; set; }
public double longitude { get; set; }
public Address2 address { get; set; }
public object comment { get; set; }
public object airport { get; set; }
}
I think you should first check whether your string is a valid Json.
You may check below link to convert to class.
How to auto-generate a C# class file from a JSON object string
You're looking for this
Using the dynamic object type. Of course you can do some casting or data mapping later on.
Have a look at JSON.Net. Download the nuget package, than use:
dynamic dyn_json = JsonConvert.DeserializeObject(json);
After that you can iterate through the dynamic object and fill your C# object.

How to parse this json in List<Class>?

I am developing windows form application in framework 4.0. I am using JSON.NET. I have the following json in a string variable. I have the 10 classes in the json as follows. How to parse the following json and convert it into List
[
{
"Class": 1,
"ClassUrl": "EngineeringSemister12014A",
"OEPTitle": "Engineer",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
],
"IsArchived": true
},
{
"Class": 7,
"ClassUrl": "Engineer2014A",
"OEPTitle": "Engineer",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
]
},
{
"Class": 8,
"ClassUrl": "Engineer22014A",
"OEPTitle": "Engineer2",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
]
},
{
"Class": 9,
"ClassUrl": "Engineer32014A",
"OEPTitle": "Engineer3",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
}
]
},
{
"Class": 10,
"ClassUrl": "Engineer32014B",
"OEPTitle": "Engineer3",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 8,
"OEPTitle": "english"
}
],
"IsRecycled": true
},
{
"Class": 12,
"ClassUrl": "Engineer52014B",
"OEPTitle": "Engineer5",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 8,
"OEPTitle": "english"
}
]
},
{
"Class": 13,
"ClassUrl": "Engineer62014B",
"OEPTitle": "Engineer6",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 8,
"OEPTitle": "english"
}
]
},
{
"Class": 16,
"ClassUrl": "Mechanical2014undefined",
"OEPTitle": "Mechanical Branch",
"Subject": [
{
"Id": 6,
"OEPTitle": "history"
},
{
"Id": 4,
"OEPTitle": "chemical "
}
]
},
{
"Class": 6,
"ClassUrl": "Engineer12014A",
"OEPTitle": "Engineer1",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 6,
"OEPTitle": "history"
},
{
"Id": 4,
"OEPTitle": "chemical "
}
]
},
{
"Class": 11,
"ClassUrl": "Engineer42014B",
"OEPTitle": "Engineer4",
"Subject": [
{
"Id": 1,
"OEPTitle": "Algebra"
},
{
"Id": 2,
"OEPTitle": "Maths"
},
{
"Id": 6,
"OEPTitle": "history"
},
{
"Id": 4,
"OEPTitle": "chemical "
},
{
"Id": 8,
"OEPTitle": "english"
}
]
}
]
Using json2csharp:
public class Subject
{
public int Id { get; set; }
public string OEPTitle { get; set; }
}
public class RootObject
{
public int Class { get; set; }
public string ClassUrl { get; set; }
public string OEPTitle { get; set; }
public List<Subject> Subject { get; set; }
public bool IsArchived { get; set; }
}
and now, you can use JSON.NET:
List<RootObject> rootObj = JsonConvert.Deserialize<List<RootObject>>(yourJsonHere);

Categories