c# - EF Core returns only first record of a list unless FK entities are reset -
i facing same issue described in question.
problem: method getallconferences()
returns correctly conferences db, when return result view controller return ok(triplistvm)
inly first collection item returned client.
on otehr side, setting null fk references (as pointed out in question above) can return correctly entities client, not seem me proper way of proceeding.
edit: solution simpler though. in code below (i leave in original form others see it) not mapping fk entities inside viewmodel dto objects, returning model entity itself. reason why needed null inner references make work.
by returning dtos objects, works properly.
have 3 entities involved 1-many relationships:
public class conference { public int id { get; set; } [required] [maxlength(50)] public string name { get; set; } public icollection<venue> venues { get; set; } public int? locationid { get; set; } public location location { get; set; } } public class venue { public int id { get; set; } [required] [maxlength(50)] public string name { get; set; } public int? conferenceid { get; set; } public trip conference { get; set; } public int? locationid { get; set; } public city city { get; set; } } public class city { public int id { get; set; } [required] [maxlength(50)] public string name { get; set; } public icollection<conference> conferences { get; set; } public icollection<venue> venues { get; set; } }
in repository, have method returns conferences , related entities (city , venues):
public ienumerable<conference> getallconferences() { return _context.conferences .include(t => t.venues) .include(t => t.city) .tolist(); }
in controller need use following code return results:
var conferences = _repository.getallconferences(); if (conferences.any()) { var conferencelistvm = trips.toconferencevmlist(); //without setting fk references null, can return first result of collection foreach (var vm in conferencelistvm) { foreach (var pm in vm.poinofinterests) { pm.trip = null; } vm.location.conferences = null; vm.location.venues = null; } return ok(conferencelistvm); } public static conferenceviewmodel toconferencevm(this conference conference) { var confvm = new conferenceviewmodel(); confvm.name = conference.name; confvm.city = conference.city; confvm.venues = conference.venues; return tripvm; } public static ienumerable<conferenceviewmodel> toconferencevmlist(this ienumerable<conference> conferences) { return conferences.select(c => c.toconferencevm()).tolist(); }
Comments
Post a Comment