public class ShipmentItem
{
public int? ShipmentId { get; set; }
public int? TotalCountShipmentItems { get; set; }
public List<PurchaseOrderItem> ShipmentItemList { get; set; }
}
public class PurchaseOrderItem
{
public int itemId{get;set}
public string ItemNumber { get; set; }
public string Description { get; set; }
public int? TotQuantity { get; set; }
}
I want the result in the format
data: [
{
ShipmentId : 15,
TotalCountShipmentItems : 4,
ShipmentItemList : [
{
itemId: 10,
ItemNumber: 1012,
Description : desss,
TotQuantity : 20,/*sum of all items of id 10*/
},
{
itemId: 11,
ItemNumber: 1013,
Description : d333s,
TotQuantity : 50,/*sum of all items of id 11*/
}
]
}]
I want result group by shipmentId then by Group by ItemId
tried to group by but not with luck on the second level but not working
It will cause sequence issue
Where am I making mistake? Can we not group it on geting list or before?
Related
Here are my simplified entities for this questions:
public class Page
{
public Guid Id { get; set; }
public string PageType { get; set; }
public string PageName { get; set; }
public virtual ICollection<Section> Sections { get; set; }
}
public class Section
{
public Guid Id { get; set; }
public string SectionName { get; set; }
public string CmsContentId { get; set; }
[NotMapped]
public ICollection<CmsContentLanguage> Languages { get; set; }
}
public class CmsContentLanguage
{
public Guid Id { get; set; }
public string LangugeCode { get; set; }
public string CmsContentId { get; set; }
}
What I want to do is query my Page table and include the Sections navigation property, and for each Section the Languages property (which is not a db column) will be a collection of CmsContentLanguages. The response from my query would look like this:
{
"id":"6b3c680a-a5aa-4782-80ce-591f1d16abe2",
"pageName":"Description",
"pageType":"content",
"sections":[
{
"id":"e688b09e-9b1c-4094-aa04-cd044c820630",
"sectionName":"Introduction",
"cmsContentId ":"e1ad5dca-c74b-497e-856b-bf26a699e635",
"languages":[
{
"id":"11e19169-797c-4b6a-b5e8-2bdb9c1f28cc",
"languageCode":"en",
"cmsContentId ":"e1ad5dca-c74b-497e-856b-bf26a699e635"
},
{
"id":"19a0f31c-4b96-4afe-920f-40cea544eeab",
"languageId":"es",
"cmsContentId ":"e1ad5dca-c74b-497e-856b-bf26a699e635"
}
]
},
{
"id":"a53b9ace-b9a7-407d-b641-7a3c46077428",
"sectionName":"FAQs",
"cmsContentId ":"e1ad5dca-c74b-497e-856b-bf26a699e635",
"languages":[
{
"id":"11e19169-797c-4b6a-b5e8-2bdb9c1f28cc",
"languageCode":"en",
"cmsContentId ":"e1ad5dca-c74b-497e-856b-bf26a699e635"
},
{
"id":"19a0f31c-4b96-4afe-920f-40cea544eeab",
"languageId":"es",
"cmsContentId ":"e1ad5dca-c74b-497e-856b-bf26a699e635"
}
]
}
]
}
Multiple Section records can have the same CmsContentId value. Section.Languages is not a navigation property (nor do I think it should be).
Then I want to do a Linq query like this:
var guidId = Guid.Parse("6b3c680a-a5aa-4782-80ce-591f1d16abe2");
var query = dbContext.Pages
.Include(x => x.Sections)
.FirstOrDefault(p => p.Id == guidId);
At this point I have the response data I want, but the Languages property of each Section entity is null. This is where I'm lost as to how to setup relationships or do a query to get this data.
You are looking for the ThenInclude method. Here is how you use it.
var query = dbContext.Pages
.Include(x => x.Sections)
.ThenInclude(x => x.Languages)
.FirstOrDefault(p => p.Id == guidId);
How do work with a model with a model property inside of it?
I am pulling info from an api successfully but it does not work after I try to change my model from int to model like below:
public class TypeModel
{
[PrimaryKey]
public int pType { get; set; }
public DepartmentModel fDepartment { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Comments { get; set; }
public string Version { get; set; }
}
Here is the department model
public class DepartmentModel
{
public int pDepartment { get; set; }
public string Name { get; set; }
}
My ViewModel had this code and was working. Been trying to make changes as I think I need to change it in here somehow.
Types.Clear();
IEnumerable<TypesModel> types = await DataSource.GetTypesAsync(typeinfo.pType, true);
foreach (var column in types)
{
Types.Add(column);
}
Here is the deserialization from the api.
IEnumerable<TypeModel> TypeEnumerator;
public async Task<IEnumerable<TypeModel>> GetTypesAsync(bool r = false)
{
if (r)
{
var j = await HttpConstructor.GetStringAsync($"api/gettypes");
return await Task.Run(() => JsonConvert.DeserializeObject<IEnumerable<TypeModel>>(j));
}
return TypeEnumerator; ;
}
Here is the json information being produced from the api for types
{
"pType": 10,
"fDepartment": 1,
"title": "Bigwig",
"description": "For the bigwigs",
"comments": "high priority",
"version": "1.2.3"
},
{
"pType": 11,
"fDepartment": 1,
"title": "Frontdesk",
"description": "front end people",
"comments": "none",
"version": "1.2.4"
}
this is what I would do. There are undoubtedly other ways to approach it
public class TypeModel
{
[PrimaryKey]
public int pType { get; set; }
public int fDepartment { get; set; }
public DepartmentModel Department { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Comments { get; set; }
public string Version { get; set; }
}
List<TypesModel> types = await DataSource.GetTypesAsync(typeinfo.pType, true);
foreach (var type in types)
{
type.Department = new DepartmentModel
{
pDepartment = type.fDeparment,
Name = "???"
};
}
Got a solution going by using a Dictionary collection and avoided adjusting the model and mess up the business logic throughout the app.
I kept the original model and created a new one called TypesModel to use for list views.
public class TypesModel
{
[PrimaryKey]
public int pType { get; set; }
public Dictionary<int, string> fDepartment { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Comments { get; set; }
public string Version { get; set; }
}
Then I used Linq join to combine the information and also fill in the dictionary values.
var query = from t in types
join d in departments
on t.fDeparment equals d.pDepartment
select new TypesModel
{
pType = t.pType,
fDepartment = new Dictionary<int, string>()
{
{ d.pDepartment, d.Name }
},
Title = t.Title,
Description = t.Description
};
I have a Product class, which looks like this:
Public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Barcode { get; set; }
public string InnerCode { get; set; }
public virtual ProductUnit ProductUnit { get; set; }
public int? ProductUnitID { get; set; }
public virtual ProductType ProductType { get; set; }
public int? ProductTypeID { get; set; }
}
In ASP.NET Core Web API Service I have a put method which returns OK(product).
The response in postman looks like this:
{
"result": {
"id": 22,
"name": "Bread",
"productType": {
"id": 4,
"name": "Food",
"remarks": null,
"products": []
},
"productTypeID": 4,
"code": "566",
"barcode": "855",
"innerCode": "145522",
"productUnit": {
"id": 4,
"name": "Box",
"remarks": null,
"products": []
},
"productUnitID": 4
},
"id": 592, ---> //probably this
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false
}
I am trying to get Product object as shown below:
var data = await httpResponseMessage.Content.ReadAsAsync<Product>();
But As a result, I get the product object with null properties, except the ID, which is random number and which as I think is the id above the exception in the json response.
What mistake do I have?
So, I believe you are trying to parse result which is the inner object in your case.
In order to parse the whole result you have to create a type for mentioned json, which you can create using https://app.quicktype.io/#l=cs&r=json2csharp.
Classes will be as follows :
public partial class ProductResult
{
[JsonProperty("result")]
public Result Result { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("exception")]
public object Exception { get; set; }
[JsonProperty("status")]
public long Status { get; set; }
[JsonProperty("isCanceled")]
public bool IsCanceled { get; set; }
[JsonProperty("isCompleted")]
public bool IsCompleted { get; set; }
[JsonProperty("isCompletedSuccessfully")]
public bool IsCompletedSuccessfully { get; set; }
[JsonProperty("creationOptions")]
public long CreationOptions { get; set; }
[JsonProperty("asyncState")]
public object AsyncState { get; set; }
[JsonProperty("isFaulted")]
public bool IsFaulted { get; set; }
}
public partial class Result
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("productType")]
public Product ProductType { get; set; }
[JsonProperty("productTypeID")]
public long ProductTypeId { get; set; }
[JsonProperty("code")]
[JsonConverter(typeof(ParseStringConverter))]
public long Code { get; set; }
[JsonProperty("barcode")]
[JsonConverter(typeof(ParseStringConverter))]
public long Barcode { get; set; }
[JsonProperty("innerCode")]
[JsonConverter(typeof(ParseStringConverter))]
public long InnerCode { get; set; }
[JsonProperty("productUnit")]
public Product ProductUnit { get; set; }
[JsonProperty("productUnitID")]
public long ProductUnitId { get; set; }
}
public partial class Product
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("remarks")]
public object Remarks { get; set; }
[JsonProperty("products")]
public List<object> Products { get; set; }
}
now you can use ProductResult as
var data = await httpResponseMessage.Content.ReadAsAsync<ProductResult>();
Update
Another solution is, instead of creating type (class) for full JSON data you can use JObject class and using jsonpath you can select any property or object as follows :
string result = await httpResponseMessage.Content.ReadAsStringAsync();
Product product = JObject.Parse(result).SelectToken("$.result").ToObject<Product>()
Im using xamarin.forms to create an app that uses the MusixMatch api. It's throwing the following exception : Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List. To my knowledge, Ive done everything correctly, not sure why this exception is being thrown. Any help will be appreciated.
TrackList.cs
public class TrackList
{
public class Track
{
public int track_id { get; set; }
public string track_mbid { get; set; }
public string track_isrc { get; set; }
public string track_spotify_id { get; set; }
public string track_soundcloud_id { get; set; }
public string track_xboxmusic_id { get; set; }
public string track_name { get; set; }
public int track_rating { get; set; }
public int track_length { get; set; }
public int commontrack_id { get; set; }
public int instrumental { get; set; }
}
public class Body
{
public IList<Track> track_list { get; set; }
}
}
Api Request
public async void SearchBtn(object sender, EventArgs e)
{
List<TrackList.Track> trans = new List<TrackList.Track>();
string search = SearchField.Text;
try
{
var content = "";
HttpClient client = new HttpClient();
var RestUrl = "http://api.musixmatch.com/ws/1.1/track.search?q_track=" + search + "&page_size=3&page=1&s_track_rating=desc";
client.BaseAddress = new Uri(RestUrl);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(RestUrl);
content = await response.Content.ReadAsStringAsync();
var items = JsonConvert.DeserializeObject<List<TrackList.Body>>(content);
listTracks.ItemsSource = items;
}
catch (Exception ex)
{
string exception = ex.Message;
}
}
The json from PostMan
{
"message": {
"header": {
"status_code": 200,
"execute_time": 0.013219118118286,
"available": 10000
},
"body": {
"track_list": [
{
"track": {
"track_id": 143296606,
"track_mbid": "",
"track_isrc": "",
"track_spotify_id": "",
"track_soundcloud_id": "",
"track_xboxmusic_id": "",
"track_name": "&Burn",
"track_name_translation_list": [],
"track_rating": 61,
"track_length": 179,
"commontrack_id": 79313332,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_lyrics_crowd": 0,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 19,
"lyrics_id": 17324950,
"subtitle_id": 19405016,
"album_id": 27788309,
"album_name": "Dont Smile At Me",
"artist_id": 34955086,
"artist_mbid": "",
"artist_name": "Billie Eilish feat. Vince Staples",
"album_coverart_100x100": "http://s.mxmcdn.net/images-storage/albums/nocover.png",
"album_coverart_350x350": "",
"album_coverart_500x500": "",
"album_coverart_800x800": "",
"track_share_url": "https://www.musixmatch.com/lyrics/Billie-Eilish-feat-Vince-Staples/burn-with-Vince-Staples?utm_source=application&utm_campaign=api&utm_medium=IT+Related%3A1409617652911",
"track_edit_url": "https://www.musixmatch.com/lyrics/Billie-Eilish-feat-Vince-Staples/burn-with-Vince-Staples/edit?utm_source=application&utm_campaign=api&utm_medium=IT+Related%3A1409617652911",
"commontrack_vanity_id": "Billie-Eilish-feat-Vince-Staples/burn-with-Vince-Staples",
"restricted": 0,
"first_release_date": "2017-12-15T00:00:00Z",
"updated_time": "2017-12-17T22:53:56Z",
"primary_genres": {
"music_genre_list": []
},
"secondary_genres": {
"music_genre_list": []
}
}
}
]
}
}
}
You're telling it to deserialize the result to a list, when actually the result is object with 1 property (message) which has 2 properties (header and body), so make sure your object structure matches. I find json2csharp extremely handy for complex structures like this.
public class TrackListResponse
{
public Message message { get; set; }
public class Header
{
public int status_code { get; set; }
public double execute_time { get; set; }
public int available { get; set; }
}
public class PrimaryGenres
{
public List<object> music_genre_list { get; set; }
}
public class SecondaryGenres
{
public List<object> music_genre_list { get; set; }
}
public class Track
{
public int track_id { get; set; }
public string track_mbid { get; set; }
public string track_isrc { get; set; }
public string track_spotify_id { get; set; }
public string track_soundcloud_id { get; set; }
public string track_xboxmusic_id { get; set; }
public string track_name { get; set; }
public List<object> track_name_translation_list { get; set; }
public int track_rating { get; set; }
public int track_length { get; set; }
public int commontrack_id { get; set; }
public int instrumental { get; set; }
public int #explicit { get; set; }
public int has_lyrics { get; set; }
public int has_lyrics_crowd { get; set; }
public int has_subtitles { get; set; }
public int has_richsync { get; set; }
public int num_favourite { get; set; }
public int lyrics_id { get; set; }
public int subtitle_id { get; set; }
public int album_id { get; set; }
public string album_name { get; set; }
public int artist_id { get; set; }
public string artist_mbid { get; set; }
public string artist_name { get; set; }
public string album_coverart_100x100 { get; set; }
public string album_coverart_350x350 { get; set; }
public string album_coverart_500x500 { get; set; }
public string album_coverart_800x800 { get; set; }
public string track_share_url { get; set; }
public string track_edit_url { get; set; }
public string commontrack_vanity_id { get; set; }
public int restricted { get; set; }
public DateTime first_release_date { get; set; }
public DateTime updated_time { get; set; }
public PrimaryGenres primary_genres { get; set; }
public SecondaryGenres secondary_genres { get; set; }
}
public class TrackList
{
public Track track { get; set; }
}
public class Body
{
public List<TrackList> track_list { get; set; }
}
public class Message
{
public Header header { get; set; }
public Body body { get; set; }
}
}
Then just deserialize to the outer object:
JsonConvert.DeserializeObject<TrackListResponse>(content);
I think you can't deserialize a single object into a collection. So you should use TrackList.Body instead of List<TrackList.Body>
So you maybe have to change this line:
var items = JsonConvert.DeserializeObject<List<TrackList.Body>>(content);
to
var items = JsonConvert.DeserializeObject<TrackList.Body>(content);
then iterate each item in items to add them to a List<TrackList.Body>
My class have a list of another class.
public class CustomerRequest : BaseEntity
{
[Key]
public int Id { get; set; }
public int Code { get; set; }
public virtual List<TechnicalOfficer> TechnicalOfficers { get; set; }
}
public class TechnicalOfficers : BaseEntity
{
[Key]
public int Id { get; set; }
public int Code { get; set; }
}
I want to select all CustomerRequest that TechnicalOfficers are contains special id.
I want to select all CustomerRequest that TechnicalOfficers are contains special id.
Use Any (or perhaps All) with Contains.
var specialIds = new[] { 1, 2, 3 };
var customerRequests = CustomerRequests
.Where(cr => cr.TechnicalOfficers.Any(to => specialIds.Contains(to.Id)));