Calculate the cumulative sum of a grouped collection - c#

This is the expected result: The accumulatedMaxPax should be equal to the previous value + the current maxPax. It should reset (=0) on every destinations change.
[
{
"date": "2022-05-06",
"destinations": [
{
"id": 1,
"description": "PAXOS - ANTIPAXOS",
"abbreviation": "PA",
"ports": [
{
"id": 1,
"description": "CORFU PORT",
"maxPax": 200,
"accumulatedMaxPax": 200 // Initial (accumulatedMaxPax = maxPax )
},
{
"id": 4,
"description": "BENITSES PORT",
"maxPax": 200,
"accumulatedMaxPax": 400 // 200 (previous) + 200 (current) = 400
},
{
"id": 17,
"description": "BOUKARI PORT",
"maxPax": 100,
"accumulatedMaxPax": 500 // 400 (previous) + 100 (current) = 500
},
{
"id": 2,
"description": "LEFKIMMI PORT",
"maxPax": 400,
"accumulatedMaxPax": 900 // 500 (previous) + 400 (current) = 900
}
]
},
{
"id": 3,
"description": "BLUE LAGOON",
"abbreviation": "BL",
"ports": [
{
"id": 1,
"description": "CORFU PORT",
"maxPax": 215,
"accumulatedMaxPax": 215
},
{
"id": 4,
"description": "BENITSES PORT",
"maxPax": 215,
"accumulatedMaxPax": 430
}
]
},
{
"id": 7,
"description": "PARTY",
"abbreviation": "PRT",
"ports": [
{
"id": 1,
"description": "CORFU PORT",
"maxPax": 200,
"accumulatedMaxPax": 200
}
]
}
]
}
]
This is the code which works according to the specs, with the missing part of the puzzle as question marks!
public IEnumerable<AvailabilityCalendarGroupVM> GetForCalendar(string fromDate, string toDate) {
return context.Schedules
.Where(x => x.Date >= Convert.ToDateTime(fromDate) && x.Date <= Convert.ToDateTime(toDate))
.GroupBy(x => x.Date)
.Select(x => new AvailabilityCalendarGroupVM {
Date = DateHelpers.DateTimeToISOString(x.Key.Date),
Destinations = x.GroupBy(x => new { x.Date, x.Destination.Id, x.Destination.Description, x.Destination.Abbreviation }).Select(x => new DestinationCalendarVM {
Id = x.Key.Id,
Description = x.Key.Description,
Abbreviation = x.Key.Abbreviation,
Ports = x.GroupBy(x => new { x.PortId, x.Port.Description, x.Port.Abbreviation, x.MaxPax, x.Port.StopOrder }).OrderBy(x => x.Key.StopOrder).Select(x => new PortCalendarVM {
Id = x.Key.PortId,
Description = x.Key.Description,
MaxPax = x.Key.MaxPax,
AccumulatedMaxPax = NOW WHAT ???
})
})
}).ToList();
}

Related

Get Rank for Contest use Entity Framework Core

I have the following database
UserId
Name
1
Jonh
2
Sam
3
Harry
ContestId
Name
1
Exam
UserId
ContestId
1
1
2
1
3
1
ExerciseId
Name
ContestId
1
Test A
1
2
Test B
1
SubmitId
ExerciseId
UserId
Point
1
1
1
10
2
1
1
20
3
2
1
30
4
2
1
40
5
1
2
50
6
1
2
80
The result I wanted
Rank
UserName
Test A
Test B
Total
1
Sam
80
0
80
2
Jonh
20
40
60
3
Harry
0
0
0
I tried:
_UserContest.Select(x => new
{
User = x.User, //foreign key
Submits = x.Contest.Exercises
.SelectMany(y => y.Submits.Where(z => z.UserId == x.UserId).OrderByDescending(z => z.Point).Take(1))
.ToList()
}).Select(x => new
{
Name = x.User.Name,
Submits = x.Submits.Select(y => new { Id = y.ExerciseId, Point = y.Point }), //This list will be formatted as a row on the UI
Total = x.Submits.Sum(y => y.Point)
}).OrderByDescending(x => x.Total).ToListAsync();
The result
[
{
"rank": 0,
"name": "Sam",
"submits": [
{
"id": "1",
"point": 80,
},
],
"total": 80,
},
{
"rank": 0,
"name": "Jonh",
"submits": [
{
"id": "1",
"point": 20,
},
{
"id": "2",
"point": 40,
},
],
"total": 60,
},
{
"rank": 0,
"name": "Harry",
"submits": [],
"total": 0,
},
]
Then, I found the library Thinktecture.EntityFrameworkCore.SqlServer support row number. I corrected my query
_UserContest.Select(x => new
{
User = x.User, //foreign key
Submits = x.Contest.Exercises
.SelectMany(y => y.Submits.Where(z => z.UserId == x.UserId).OrderByDescending(z => z.Point).Take(1))
.ToList()
}).Select(x => new
{
Rank = EF.Functions.RowNumber(EF.Functions.OrderByDescending(x.Submits.Sum(y => y.Point))),
Name = x.User.Name,
Submits = x.Submits.Select(y => new { Id = y.ExerciseId, Point = y.Point }), //This list will be formatted as a row on the UI
Total = x.Submits.Sum(y => y.Point)
}).ToListAsync();
But, it's not what i expected
[
{
"rank": 1,
"name": "Sam",
"submits": [
{
"id": "1",
"point": 80,
},
],
"total": 80,
},
{
"rank": 2,
"name": "Jonh",
"submits": [
{
"id": "1",
"point": 20,
},
{
"id": "2",
"point": 40,
},
],
"total": 60,
},
{
"rank": 4, //it's exactly 3
"name": "Harry",
"submits": [],
"total": 0,
},
]
Please help me fix it or a better query, thanks.

Selenium - json - c#

var pre1 = driver.FindElementByTagName("pre").Text.Replace(#"\", "").Trim();
dynamic root = JsonConvert.DeserializeObject(pre1);
I have this JSON response:
{
"success": true,
"message": null,
"outright": false,
"eventId": 0,
"si": 111,
"leonard": [{
"catalog":[0,0,0,0,0,0],
"edit": 25965112,
"mkilo": {
"888;315;2;3;0": {
"id": 1000,
"description": "Car"
},
"888;316;2;4;0": {
"id": 1001,
"description": "Train"
},
"888;317;2;5;0": {
"id": 1002,
"description": "Airplane"
}
},
"ti": "008000",
"checkin": 254,
"searchCar": {
"id": 1000,
"description": "Car"
}
}],
"ti": 149498
}
verified with jsonlint
root.leonard[0].catalog.Count = 6 ---- > OK
but
root.leonard[0].mkilo.Count = null - -- Why?
I want to read the contents of mkilo.

ElasticSearch - different result ordering for simple request and aggregation request (NEST)

I have a search page which contains two search result types: summary result and concrete result.
Summary result page contains top 3 result per category (top hits)
Concrete result page contains all result for a selected category.
To obtain the Summary page I use the request:
var searchDescriptor = new SearchDescriptor<ElasticType>();
searchDescriptor.Index("index_name")
.Query(q =>
q.MultiMatch(m => m
.Fields(fs => fs
.Field(f => f.Content1, 3)
.Field(f => f.Content2, 2)
.Field(f => f.Content3, 1))
.Fuzziness(Fuzziness.EditDistance(1))
.Query(query)
.Boost(1.1)
.Slop(2)
.PrefixLength(1)
.MaxExpansions(100)
.Operator(Operator.Or)
.MinimumShouldMatch(2)
.FuzzyRewrite(RewriteMultiTerm.ConstantScoreBoolean)
.TieBreaker(1.0)
.CutoffFrequency(0.5)
.Lenient()
.ZeroTermsQuery(ZeroTermsQuery.All))
&& (q.Terms(t => t.Field(f => f.LanguageId).Terms(1)) || q.Terms(t => t.Field(f => f.LanguageId).Terms(0))))
.Aggregations(a => a
.Terms("category", tagd => tagd
.Field(f => f.Category)
.Size(10)
.Aggregations(aggs => aggs.TopHits("top_tag_hits", t => t.Size(3)))))
.FielddataFields(fs => fs
.Field(p => p.Content1, 3)
.Field(p => p.Content2, 2)
.Field(p => p.Content3, 1));
var elasticResult = _elasticClient.Search<ElasticType>(_ => searchDescriptor);
And I get result, for example
{
"aggregations": {
"category": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": "category1",
"doc_count": 40,
"top_tag_hits": {
"hits": {
"total": 40,
"max_score": 5.4,
"hits": [{
"_index": "...",
"_type": "...",
"_id": "...",
"_score": 5.4,
"_source": {
"id": 1
}
},
{
"_index": "...",
"_type": "...",
"_id": "...",
"_score": 4.3,
"_source": {
"id": 3 // FAIL!
}
},
{
"_index": "...",
"_type": "...",
"_id": "...",
"_score": 4.3,
"_source": {
"id": 2
}
}]
}
}
}]
}
}
}
So i get few hits with the same _score.
To obtain the concrete result (by category) page I use the request:
var searchDescriptor = new SearchDescriptor<ElasticType>();
searchDescriptor.Index("index_name")
.Size(perPage <= 0 ? 100 : perPage)
.From(page * perPage)
.Query(q => q
.MultiMatch(m => m
.Fields(fs => fs
.Field(f => f.Content1, 3)
.Field(f => f.Content2, 2)
.Field(f => f.Content3, 1)
.Field(f => f.Category))
.Fuzziness(Fuzziness.EditDistance(1))
.Query(searchRequest.Query)
.Boost(1.1)
.Slop(2)
.PrefixLength(1)
.MaxExpansions(100)
.Operator(Operator.Or)
.MinimumShouldMatch(2)
.FuzzyRewrite(RewriteMultiTerm.ConstantScoreBoolean)
.TieBreaker(1.0)
.CutoffFrequency(0.5)
.Lenient()
.ZeroTermsQuery(ZeroTermsQuery.All))
&& q.Term(t => t.Field(f => f.Category).Value(searchRequest.Category))
&& (q.Terms(t => t.Field(f => f.LanguageId).Terms(1)) || q.Terms(t => t.Field(f => f.LanguageId).Terms(0))))
.FielddataFields(fs => fs
.Field(p => p.Content1, 3)
.Field(p => p.Content2, 2)
.Field(p => p.Content3, 1))
.Aggregations(a => a
.Terms("category", tagd => tagd
.Field(f => f.Category)));
And the result something like this:
{
"hits": {
"total": 40,
"max_score": 7.816723,
"hits": [{
"_index": "...",
"_type": "...",
"_id": "...",
"_score": 7.816723,
"_source": {
"id": 1
}
},
{
"_index": "...",
"_type": "...",
"_id": "...",
"_score": 6.514713,
"_source": {
"id": 2
}
},
{
"_index": "...",
"_type": "...",
"_id": "...",
"_score": 6.514709,
"_source": {
"id": 3
}
}]
}
}
And so in the second case, for a specific category I get the _score with great precision and elastic can easily sort the results correctly. But in the case of aggregation there are results with the same _score, and in this case, the sorting is not clear how it works.
Can someone direct me to the right path how to solve this problem? or how can I achieve the same order in the results? Maybe I can increase the accuracy for the aggregated results?
I use elasticsearch server version "5.3.0" and NEST library version "5.0.0".
Update:
Native query for aggregation request:
{
"fielddata_fields": [
"content1^3",
"content2^2",
"content3^1"
],
"aggs": {
"category": {
"terms": {
"field": "category",
"size": 10
},
"aggs": {
"top_tag_hits": {
"top_hits": {
"size": 3
}
}
}
}
},
"query": {
"bool": {
"must": [
{
"multi_match": {
"boost": 1.1,
"query": "sparta",
"fuzzy_rewrite": "constant_score_boolean",
"fuzziness": 1,
"cutoff_frequency": 0.5,
"prefix_length": 1,
"max_expansions": 100,
"slop": 2,
"lenient": true,
"tie_breaker": 1.0,
"minimum_should_match": 2,
"operator": "or",
"fields": [
"content1^3",
"content2^2",
"content3^1"
],
"zero_terms_query": "all"
}
},
{
"bool": {
"should": [
{
"terms": {
"languageId": [
1
]
}
},
{
"terms": {
"languageId": [
0
]
}
}
]
}
}
]
}
}
}
Native query for concrete request:
{
"from": 0,
"size": 100,
"fielddata_fields": [
"content1^3",
"content2^2",
"content3^1"
],
"aggs": {
"category": {
"terms": {
"field": "category"
}
}
},
"query": {
"bool": {
"must": [
{
"bool": {
"must": [
{
"multi_match": {
"boost": 1.1,
"query": ".....",
"fuzzy_rewrite": "constant_score_boolean",
"fuzziness": 1,
"cutoff_frequency": 0.5,
"prefix_length": 1,
"max_expansions": 100,
"slop": 2,
"lenient": true,
"tie_breaker": 1.0,
"minimum_should_match": 2,
"operator": "or",
"fields": [
"content1^3",
"content2^2",
"content3^1",
"category"
],
"zero_terms_query": "all"
}
},
{
"term": {
"category": {
"value": "category1"
}
}
}
]
}
},
{
"bool": {
"should": [
{
"terms": {
"languageId": [
1
]
}
},
{
"terms": {
"languageId": [
0
]
}
}
]
}
}
]
}
}
}
Also i use next mapping for creating index:
var descriptor = new CreateIndexDescriptor(indexName)
.Mappings(ms => ms
.Map<ElasticType>(m => m
.Properties(ps => ps
.Keyword(s => s.Name(ecp => ecp.Title))
.Text(s => s.Name(ecp => ecp.Content1))
.Text(s => s.Name(ecp => ecp.Content2))
.Text(s => s.Name(ecp => ecp.Content3))
.Date(s => s.Name(ecp => ecp.Date))
.Number(s => s.Name(ecp => ecp.LanguageId).Type(NumberType.Integer))
.Keyword(s => s.Name(ecp => ecp.Category))
.Text(s => s.Name(ecp => ecp.PreviewImageUrl).Index(false))
.Text(s => s.Name(ecp => ecp.OptionalContent).Index(false))
.Text(s => s.Name(ecp => ecp.Url).Index(false)))));
_elasticClient.CreateIndex(indexName, _ => descriptor);
Your query has problems.
What you are using is combination of must and should inside a must as part of bool query.
So if you read more in this link, you can see for must
The clause (query) must appear in matching documents and will contribute to the score.
so it will five equal scoring to all your documents which matched the condition. Any other condition which didn't match the condition won't even be there in results to score.
What you should do it use should query but outside of must query, so Elasticsearch will be able to score your documents correctly
For more info as part of this question
Can someone direct me to the right path how to solve this problem?
you should pass 'explain': true in the query. You can read more about explain query and how to interpret results in this link.
You answer for this question is
how can I achieve the same order in the results?
As every score is same therefore Elasticsearch can sort the result in any way it gets the response from its nodes.
Possible Solution:
You should reorganize your query to make real use of should query and its boosting capabilities. You can read more about boosting here.
I tried two query similar to yours but with correct usage of should and they gave me same order as expected. Your both query should be constructed as below:
{
"from": 0,
"size": 10,
"_source": [
"content1^3",
"content2^2",
"content3^1"
],
"query": {
"bool": {
"should": [
{
"match": {
"languageId": 1
}
},
{
"match": {
"languageId": 0
}
}
],
"must": [
{
"multi_match": {
"boost": 1.1,
"query": ".....",
"fuzzy_rewrite": "constant_score_boolean",
"fuzziness": 1,
"cutoff_frequency": 0.5,
"prefix_length": 1,
"max_expansions": 100,
"slop": 2,
"lenient": true,
"tie_breaker": 1,
"minimum_should_match": 2,
"operator": "or",
"fields": [
"content1^3",
"content2^2",
"content3^1",
"category"
],
"zero_terms_query": "all"
}
}
]
}
}
}
and second query as
{
"size": 0,
"query": {
"bool": {
"should": [
{
"match": {
"languageId": 1
}
},
{
"match": {
"languageId": 0
}
}
],
"must": [
{
"multi_match": {
"boost": 1.1,
"query": ".....",
"fuzzy_rewrite": "constant_score_boolean",
"fuzziness": 1,
"cutoff_frequency": 0.5,
"prefix_length": 1,
"max_expansions": 100,
"slop": 2,
"lenient": true,
"tie_breaker": 1,
"minimum_should_match": 2,
"operator": "or",
"fields": [
"content1^3",
"content2^2",
"content3^1",
"category"
],
"zero_terms_query": "all"
}
}
]
}
},
"aggs": {
"categories": {
"terms": {
"field": "category",
"size": 10
},
"aggs": {
"produdtcs": {
"top_hits": {
"_source": [
"content1^3",
"content2^2",
"content3^1"
],
"size": 3
}
}
}
}
}
}

c# linq-to-sql EF query to match a particular JSON structure

I've JSON with the following structure:
[
{
"ID": 1,
"Label": "Reg Scheme",
"Colours": [
{
"ID": 1,
"Value": "0x3333cc",
"Result": 1,
"Label": null
},
{
"ID": 2,
"Value": "0x666699",
"Result": 2,
"Label": null
},
{
"ID": 3,
"Value": "0x009966",
"Result": 3,
"Label": null
}
]
},
{
"ID": 2,
"Label": "Spesh Scheme",
"Colours": [
{
"ID": 11,
"Value": "0x59699c",
"Result": 1,
"Label": null
},
{
"ID": 12,
"Value": "0x0070ff",
"Result": 2,
"Label": null
},
{
"ID": 13,
"Value": "0x90865e",
"Result": 3,
"Label": null
}
]
},
and I have an entity dataset whereby I've joined all the relevant information, and am attempting to produce JSON with that structure via a single linq-to-sql EF query to be returned to the webapi method.
My query so far is:
return
DbContext.Schemes
.Join(
DbContext.SchemeColours,
s => s.SchemeID,
sc => sc.SchemeID,
(s, sc) => new
{
s.SchemeID,
s.Label,
sc.Colour,
sc.Result,
sc.ColourID
})
.Select(a =>
new Overlay.ReportColourScheme
{
ID = a.SchemeID,
Label = a.Label,
Colours = new List<Overlay.ReportColour>
{
new Overlay.ReportColour
{
ID = a.ColourID,
Value = a.Colour,
Result = a.Result
}
}
})
.ToArray();
Which is almost there but not quite:
[
{
"ID": 1,
"Label": "Regular Scheme",
"Colours": [
{
"ID": 1,
"Value": "0x3333cc",
"Result": 1,
"Label": null
}
]
},
{
"ID": 1,
"Label": "Regular Scheme",
"Colours": [
{
"ID": 2,
"Value": "0x666699",
"Result": 2,
"Label": null
}
]
},
{
"ID": 1,
"Label": "Regular Scheme",
"Colours": [
{
"ID": 3,
"Value": "0x009966",
"Result": 3,
"Label": null
}
]
},
{
"ID": 2,
"Label": "Protanopia adjusted Scheme",
"Colours": [
{
"ID": 11,
"Value": "0x59699c",
"Result": 1,
"Label": null
}
]
},
{
"ID": 2,
"Label": "Protanopia adjusted Scheme",
"Colours": [
{
"ID": 12,
"Value": "0x0070ff",
"Result": 2,
"Label": null
}
]
},
{
"ID": 2,
"Label": "Protanopia adjusted Scheme",
"Colours": [
{
"ID": 13,
"Value": "0x90865e",
"Result": 3,
"Label": null
}
]
},
As of course it creates a new list for every resultID. The top-level ID is a SchemeID- what I'm looking for is logic along the lines of: "take the first 3 Results with a particular schemeID, add them to a list in Colours, then move on to the next schemeID"
I believe this will produce identical JSON that I started the post with.
Any assistance at all would be greatly appreciated, thank you.
Try the following code:
return
DbContext.Schemes
.Join(
DbContext.SchemeColours,
s => s.SchemeID,
sc => sc.SchemeID,
(s, sc) => new
{
s.SchemeID,
s.Label,
sc.Colour,
sc.Result,
sc.ColourID
})
// After joining you group by SchemeID, in this way you have
// for each SchemeID the group of related items
.GroupBy(a => a.SchemeID)
// You then create your result, starting from the main object
.Select(g =>
new Overlay.ReportColourScheme
{
ID = g.Key,
// I suppose you have at least a child for each SchemeID,
// otherwise you can check if the list is empty
Label = g.FirstOrDefault().Label,
// For each group you create a list of child object
Colours = g.Select(v => new Overlay.ReportColour
{
ID = v.ColourID,
Value = v.Colour,
Result = v.Result
}).ToList()
})
.ToArray();
The main issue is that you are using a Join where actually you need a Group Join:
return DbContext.Schemes
.GroupJoin(DbContext.SchemeColours,
s => s.SchemeID,
sc => sc.SchemeID,
(s, colours) => new Overlay.ReportColourScheme
{
ID = s.SchemeID,
Label = s.Label,
Colours = colours
.Select(sc => new Overlay.ReportColour
{
ID = sc.ColourID,
Value = sc.Colour,
Result = sc.Result,
})
.ToList()
})
.ToArray();
But since you are using Entity Framework, it would be much better and eaiser if you define (if you already haven't) and use a navigation property:
class Scheme
{
// ...
public ICollection<SchemeColour> Colours { get; set; }
}
and then simply
return DbContext.Schemes
.Select(s => new Overlay.ReportColourScheme
{
ID = s.SchemeID,
Label = s.Label,
Colours = s.Colours
.Select(sc => new Overlay.ReportColour
{
ID = sc.ColourID,
Value = sc.Colour,
Result = sc.Result,
})
.ToList()
})
.ToArray();

C# Backend Pro Is needed ! Data weirdness

Here's my Code
public Tournament Read(int id)
{
using (var context = new DragonLairContext())
{
Tournament tournament = context.Tournaments
.Include(a => a.Game)
.Include(g => g.Game.Genre)
.Include(b => b.Groups.Select(g => g.Teams))
.Include(k => k.Groups.Select(y => y.Teams.Select(l => l.Players)))
.Include(c => c.TournamentType)
.FirstOrDefault(d => d.Id == id);
return tournament;
}
}
I'm using API and due to serialization issues, I need to convert my entities to DTOobject.
Here's a snippet from the Dto Converter
public override DTOTournament Convert(Tournament t)
{
if (t.Game == null || t.TournamentType == null || t.Groups == null) throw new ArgumentException("Missing some data");
DTOTournament dtoTournament = new DTOTournament();
List<DTOGroup> dtoGroups = new List<DTOGroup>();
DTOTournamentType dtoTournamentType = new DTOTournamentType() { Id = t.TournamentType.Id, Type = t.TournamentType.Type };
foreach (var group in t.Groups)
{
if (group.Teams == null) return dtoTournament;
List<DTOTeam> dtoTeams = new List<DTOTeam>();
foreach (var team in group.Teams)
{
List<DTOPlayer> dtoPlayers = new List<DTOPlayer>();
if (team.Players == null) return dtoTournament;
foreach (var player in team.Players)
{
dtoPlayers.Add(new DTOPlayer() { Id = player.Id, Name = player.Name });
}
dtoTeams.Add(new DTOTeam()
{
Id = team.Id,
Name = team.Name,
Win = team.Win,
Loss = team.Loss,
Draw = team.Draw,
DtoPlayers = dtoPlayers
});
}
dtoGroups.Add(new DTOGroup()
{
Id = group.Id,
Name = group.Name,
DtoTeams = dtoTeams,
DtoTournament = dtoTournament
});
}
dtoTournament.DTOTournamentType = dtoTournamentType;
dtoTournament.Id = t.Id;
dtoTournament.Name = t.Name;
dtoTournament.StartDate = t.StartDate;
dtoTournament.DtoGroups = dtoGroups;
dtoTournament.DtoGame = new DTOGame() { Id = t.Game.Id, Name = t.Game.Name, DtoGenre = new DTOGenre() { Id = t.Game.Genre.Id, Name = t.Game.Genre.Name } };
return dtoTournament;
}
Here's the Json
{
"$id": "1",
"Id": 1,
"Name": "I'm a Tournament",
"StartDate": "2015-12-08T00:00:00",
"DTOTournamentType": {
"$id": "2",
"Id": 1,
"Type": "I'm type 2vs2",
"DtoTournaments": null
},
"DtoGroups": [
{
"$id": "3",
"Id": 1,
"Name": "I'm a Group",
"DtoTournament": {
"$ref": "1"
},
"DtoTeams": [
{
"$id": "4",
"Id": 1,
"Draw": 0,
"Loss": 0,
"Win": 0,
"Name": "I'm a Team",
"DtoPlayers": [
{
"$id": "5",
"Id": 1,
"Name": "I'm a Group",
"DtoTeams": null
}
],
"DtoGroups": null
},
{
"$id": "6",
"Id": 2,
"Draw": 0,
"Loss": 0,
"Win": 0,
"Name": "I'm a Team",
"DtoPlayers": [
{
"$id": "7",
"Id": 1,
"Name": "I'm a Group",
"DtoTeams": null
}
],
"DtoGroups": null
}
]
}
],
"DtoGame": {
"$id": "8",
"Id": 1,
"Name": "Im a Game - Wars",
"DtoGenre": {
"$id": "9",
"Id": 1,
"Name": "I'm Genre Roleplaying",
"DtoGames": null
},
"DtoTournaments": null
}
}
My DB contains 3 players - note converted to json
[
{
"$id": "1",
"Id": 1,
"Name": "I'm player Søren",
"DtoTeams": [
{
"$id": "2",
"Id": 1,
"Draw": 0,
"Loss": 0,
"Win": 0,
"Name": "I'm a Team",
"DtoPlayers": null,
"DtoGroups": null
}
]
},
{
"$id": "3",
"Id": 2,
"Name": "I'm player Mark",
"DtoTeams": [
{
"$id": "4",
"Id": 1,
"Draw": 0,
"Loss": 0,
"Win": 0,
"Name": "I'm a Team",
"DtoPlayers": null,
"DtoGroups": null
}
]
},
{
"$id": "5",
"Id": 3,
"Name": "I'm player René",
"DtoTeams": [
{
"$id": "6",
"Id": 2,
"Draw": 0,
"Loss": 0,
"Win": 0,
"Name": "I'm a Team",
"DtoPlayers": null,
"DtoGroups": null
}
]
}
]
So my problem which I really can't figure out. How come my DtoPlayer.Name has the same name as DtoGroup.Name. Have a look at my includes.
This exception is thrown because you are trying to use a property that was not retrieved from the database after you have disposed the database context. You can see the data while debugging because the variable is defined inside the using scope. You should also fetch the Teams on Group class.
using (var context = new DragonLairContext())
{
Tournament tournament = context.Tournaments
.Include(a => a.Game)
.Include(g => g.Game.Genre)
.Include(b => b.Groups.Select(g => g.Teams))
.Include(c => c.TournamentType)
.FirstOrDefault(d => d.Id == id);
return tournament;
}
Since you said that you could see data in debug mode, try this method.
Tournament tournament = context.Tournaments
.Include(a => a.Game)
.Include(g => g.Game.Genre)
.Include(b => b.Groups)
.Include(c => c.TournamentType).ToList()
.FirstOrDefault(d => d.Id == id);

Categories

Resources