How to reference a nested array in a XAML Binding? - xaml

I have a complex model of data based on reading in a JSON file which has a collection of objects, properties and arrays.
I am reading my data into a model which I am populating with design-time data and instantiating in my UWP project in XAML like this:
<local:UntappdUserInfoSampleData x:Key="data1" />
I want to set the ItemsSource for a ListView control to a collection in my model but I'm not sure how to reference it in my data Binding.
My object model has this structure:
user
checkins
items[]
venue
venue_name
comments
badges
items[]
badge_id
badge_description
badge_image
small
medium
large
I want to get to badge_image.small within that stack as a Binding within my XAML.
I know how to get to higher level data like this to get to checkins.items[]:
<ListView x:Name="lvRecenCheckins"
d:DataContext="{StaticResource data1}"
ItemsSource="{Binding checkins.items}"
CanDragItems="False"
IsItemClickEnabled="True"
IsSwipeEnabled="False"
SelectionMode="None" ItemTemplate="{StaticResource RecentCheckinsTemplate}" Grid.Row="1"
/>
But how can I get all the way down to the items collection for checkins.items[].badges.items[]?
I can get to the collection I want in code behind with this as an example:
UntappdUserInfoSampleData usersampleinfo = new UntappdUserInfoSampleData();
string iii2 = usersampleinfo.checkins.items[].badges.items[0].badge_image.small;
I want to bind a different ListView to checkins.items[].badges.items[]
How can I do that?
Here are the data classes:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace UntappdExplorer
{
public class UntappdUserInfoSampleData : User_User {
public UntappdUserInfoSampleData()
{
string[] names = this.GetType().GetTypeInfo().Assembly.GetManifestResourceNames();
Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("UntappdExplorer.DataModel.ricke_User_info.json");
string result = String.Empty;
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
var resolver = new DefaultContractResolver(); // Cache for performance
var Serializersettings = new JsonSerializerSettings
{
ContractResolver = resolver,
Converters = { new IgnoreUnexpectedArraysConverter(resolver) },
};
User_RootObject rootJSON = JsonConvert.DeserializeObject<User_RootObject>(result, Serializersettings);
User_User userinfo = rootJSON.response.user;
uid = userinfo.uid;
id = userinfo.id;
user_name = userinfo.user_name;
first_name = userinfo.first_name;
last_name = userinfo.last_name;
user_avatar = userinfo.user_avatar;
user_avatar_hd = userinfo.user_avatar_hd;
user_cover_photo = userinfo.user_cover_photo;
user_cover_photo_offset = userinfo.user_cover_photo_offset;
is_private = userinfo.is_private;
location = userinfo.location;
url = userinfo.url;
bio = userinfo.bio;
is_supporter = userinfo.is_supporter;
is_moderator = userinfo.is_moderator;
relationship = userinfo.relationship;
block_status = userinfo.block_status;
untappd_url = userinfo.untappd_url;
account_type = userinfo.account_type;
stats = userinfo.stats;
recent_brews = userinfo.recent_brews;
checkins = userinfo.checkins;
media = userinfo.media;
contact = userinfo.contact;
date_joined = userinfo.date_joined;
settings = userinfo.settings;
}
}
public class User_User
{
public int uid { get; set; }
public int id { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string user_avatar { get; set; }
public string user_avatar_hd { get; set; }
public string user_cover_photo { get; set; }
public int user_cover_photo_offset { get; set; }
public int is_private { get; set; }
public string location { get; set; }
public string url { get; set; }
public string bio { get; set; }
public int is_supporter { get; set; }
public int is_moderator { get; set; }
public string relationship { get; set; }
public string block_status { get; set; }
public string untappd_url { get; set; }
public string account_type { get; set; }
public User_Stats stats { get; set; }
public User_RecentBrews recent_brews { get; set; }
public User_Checkins checkins { get; set; }
public User_Media2 media { get; set; }
public List<object> contact { get; set; }
public string date_joined { get; set; }
public User_Settings settings { get; set; }
}
public class User_RootObject
{
public User_Meta meta { get; set; }
public User_Notifications notifications { get; set; }
public User_Response response { get; set; }
}
public class User_Response
{
public User_User user { get; set; }
}
public class User_ResponseTime
{
public double time { get; set; }
public string measure { get; set; }
}
public class User_InitTime
{
public int time { get; set; }
public string measure { get; set; }
}
public class User_Meta
{
public int code { get; set; }
public User_ResponseTime response_time { get; set; }
public User_InitTime init_time { get; set; }
}
public class User_UnreadCount
{
public int comments { get; set; }
public int toasts { get; set; }
public int friends { get; set; }
public int messages { get; set; }
public int venues { get; set; }
public int veunes { get; set; }
public int others { get; set; }
public int news { get; set; }
}
public class User_Notifications
{
public string type { get; set; }
public User_UnreadCount unread_count { get; set; }
}
public class User_Stats
{
public int total_badges { get; set; }
public int total_friends { get; set; }
public int total_checkins { get; set; }
public int total_beers { get; set; }
public int total_created_beers { get; set; }
public int total_followings { get; set; }
public int total_photos { get; set; }
}
public class User_Beer
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public double beer_abv { get; set; }
public string beer_description { get; set; }
public string beer_style { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact contact { get; set; }
public User_Location location { get; set; }
public int brewery_active { get; set; }
}
public class User_Item
{
public User_Beer beer { get; set; }
public User_Brewery brewery { get; set; }
}
public class User_RecentBrews
{
public int count { get; set; }
public List<User_Item> items { get; set; }
}
public class User_User2
{
public int uid { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string location { get; set; }
public int is_supporter { get; set; }
public string url { get; set; }
public string bio { get; set; }
public string relationship { get; set; }
public string user_avatar { get; set; }
public int is_private { get; set; }
public List<object> contact { get; set; }
}
public class User_Beer2
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public string beer_style { get; set; }
public string beer_slug { get; set; }
public double beer_abv { get; set; }
public int beer_active { get; set; }
public bool has_had { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact2
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location2
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery2
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact2 contact { get; set; }
public User_Location2 location { get; set; }
public int brewery_active { get; set; }
}
public class User_Comments
{
public int total_count { get; set; }
public int count { get; set; }
public List<object> items { get; set; }
}
public class User_User3
{
public int uid { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string bio { get; set; }
public string location { get; set; }
public string user_avatar { get; set; }
public string account_type { get; set; }
public List<object> venue_details { get; set; }
public object brewery_details { get; set; }
public string user_link { get; set; }
}
public class User_Item3
{
public int uid { get; set; }
public User_User3 user { get; set; }
public int like_id { get; set; }
public bool like_owner { get; set; }
public string created_at { get; set; }
}
public class User_Toasts
{
public int total_count { get; set; }
public int count { get; set; }
public bool auth_toast { get; set; }
public List<User_Item3> items { get; set; }
}
public class User_Media
{
public int count { get; set; }
public List<object> items { get; set; }
}
public class User_Source
{
public string app_name { get; set; }
public string app_website { get; set; }
}
public class User_Badges
{
public bool retro_status { get; set; }
public int count { get; set; }
public List<Item4> items { get; set; }
}
public class Item4
{
public int badge_id { get; set; }
public int user_badge_id { get; set; }
public string badge_name { get; set; }
public string badge_description { get; set; }
public string created_at { get; set; }
public BadgeImage badge_image { get; set; }
}
public class BadgeImage
{
public string sm { get; set; }
public string md { get; set; }
public string lg { get; set; }
}
public class User_Item2
{
public int checkin_id { get; set; }
public string created_at { get; set; }
public string checkin_comment { get; set; }
public double rating_score { get; set; }
public User_User2 user { get; set; }
public User_Beer2 beer { get; set; }
public User_Brewery2 brewery { get; set; }
////public object venue { get; set; }
public User_Venue venue { get; set; }
public User_Comments comments { get; set; }
public User_Toasts toasts { get; set; }
public User_Media media { get; set; }
public User_Source source { get; set; }
public User_Badges badges { get; set; }
}
//public class User_Venue
//{
// public int venue_id { get; set; }
// public string venue_name { get; set; }
// public string venue_slug { get; set; }
// public string primary_category { get; set; }
// public string parent_category_id { get; set; }
// public User_Categories categories { get; set; }
// public User_Location3 location { get; set; }
// public User_Contact3 contact { get; set; }
// public User_Foursquare foursquare { get; set; }
// public User_VenueIcon venue_icon { get; set; }
// public bool is_verified { get; set; }
//}
//public class User_Categories
//{
// public int count { get; set; }
// public List<User_Item3> items { get; set; }
//}
//public class User_Foursquare
//{
// public string foursquare_id { get; set; }
// public string foursquare_url { get; set; }
//}
public class User_Pagination
{
public string since_url { get; set; }
public string next_url { get; set; }
public int max_id { get; set; }
}
public class User_Checkins
{
public int count { get; set; }
public List<User_Item2> items { get; set; }
public User_Pagination pagination { get; set; }
}
public class User_Photo
{
public string photo_img_sm { get; set; }
public string photo_img_md { get; set; }
public string photo_img_lg { get; set; }
public string photo_img_og { get; set; }
}
public class User_User4
{
public int uid { get; set; }
public string user_name { get; set; }
public string location { get; set; }
public string bio { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string user_avatar { get; set; }
public string account_type { get; set; }
public object url { get; set; }
}
public class User_Beer3
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public double beer_abv { get; set; }
public string beer_style { get; set; }
public string beer_description { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact3
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location3
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery3
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact3 contact { get; set; }
public User_Location3 location { get; set; }
public int brewery_active { get; set; }
}
public class User_Item5
{
public string category_name { get; set; }
public string category_id { get; set; }
public bool is_primary { get; set; }
}
public class User_Categories
{
public int count { get; set; }
public List<User_Item5> items { get; set; }
}
public class User_Location4
{
public string venue_address { get; set; }
public string venue_city { get; set; }
public string venue_state { get; set; }
public string venue_country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Contact4
{
public string twitter { get; set; }
public string venue_url { get; set; }
}
public class User_Foursquare
{
public string foursquare_id { get; set; }
public string foursquare_url { get; set; }
}
public class User_VenueIcon
{
public string sm { get; set; }
public string md { get; set; }
public string lg { get; set; }
}
public class User_Venue
{
public int venue_id { get; set; }
public string venue_name { get; set; }
public string venue_slug { get; set; }
public string primary_category { get; set; }
public string parent_category_id { get; set; }
public User_Categories categories { get; set; }
public User_Location4 location { get; set; }
public User_Contact4 contact { get; set; }
public User_Foursquare foursquare { get; set; }
public User_VenueIcon venue_icon { get; set; }
public bool is_verified { get; set; }
}
public class User_Item4
{
public int photo_id { get; set; }
public User_Photo photo { get; set; }
public string created_at { get; set; }
public int checkin_id { get; set; }
public User_User4 user { get; set; }
public User_Beer3 beer { get; set; }
public User_Brewery3 brewery { get; set; }
public User_Venue venue { get; set; }
}
public class User_Media2
{
public int count { get; set; }
public List<User_Item4> items { get; set; }
}
public class User_Badge
{
public int badges_to_facebook { get; set; }
public int badges_to_twitter { get; set; }
}
public class User_Checkin
{
public int checkin_to_facebook { get; set; }
public int checkin_to_twitter { get; set; }
public int checkin_to_foursquare { get; set; }
}
public class User_Navigation
{
public int default_to_checkin { get; set; }
}
public class User_Settings
{
public User_Badge badge { get; set; }
public User_Checkin checkin { get; set; }
public User_Navigation navigation { get; set; }
public string email_address { get; set; }
}
public class AvailableColor
{
public string name { get; set; }
public string color { get; set; }
public List<int> values { get; set; }
}
public class MainItems
{
public string ItemName { get; set; }
public ObservableCollection<SubItems> SubItemsList { get; set; }
}
public class SubItems
{
public string SubItemName { get; set; }
}
public class IgnoreUnexpectedArraysConverter<T> : IgnoreUnexpectedArraysConverterBase
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
public class IgnoreUnexpectedArraysConverter : IgnoreUnexpectedArraysConverterBase
{
readonly IContractResolver resolver;
public IgnoreUnexpectedArraysConverter(IContractResolver resolver)
{
if (resolver == null)
throw new ArgumentNullException();
this.resolver = resolver;
}
public override bool CanConvert(Type objectType)
{
if (objectType.IsPrimitive || objectType == typeof(string))
return false;
return resolver.ResolveContract(objectType) is JsonObjectContract;
}
}
public abstract class IgnoreUnexpectedArraysConverterBase : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType);
if (!(contract is JsonObjectContract))
{
throw new JsonSerializationException(string.Format("{0} is not a JSON object", objectType));
}
do
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType == JsonToken.Comment)
continue;
else if (reader.TokenType == JsonToken.StartArray)
{
var array = JArray.Load(reader);
if (array.Count > 0)
throw new JsonSerializationException(string.Format("Array was not empty."));
return existingValue ?? contract.DefaultCreator();
}
else if (reader.TokenType == JsonToken.StartObject)
{
// Prevent infinite recursion by using Populate()
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
return existingValue;
}
else
{
throw new JsonSerializationException(string.Format("Unexpected token {0}", reader.TokenType));
}
}
while (reader.Read());
throw new JsonSerializationException("Unexpected end of JSON.");
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
///// END OF CLASSES /////////
}
Thanks,
Rick

Since you have nesting what you can do is show the checkins.items[] in the listview like you are showing now and once the user selects an "item" from the checkins (i.e, an item from the listView), within the Tapped or SelectionChanged event of the list view get the selected item and show its list of "badge" items in a new listView.
private void lvRecenCheckins_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedCheckinItem = (sender as items).badges;
newListView.ItemSource = selectedCheckinItem.items;
}
Please note : this is based on the information that is provided in the question, actual class names might differ.
Hope this helps..! Do ask if you have any queries..

maybe you can have a look here: https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
I would try something like this:
<DataTemplate x:DataType="local:YourClass">
<Grid>
<TextBlock Text="{x:Bind GetFirstBadgeItemSmall(badges)}" />
</Grid>
</DataTemplate>
In your code behind, aka ViewModel you need to implement a new Method:
public string GetFirstBadgeItemSmall(IEnumerable<badge> badges)
{
return (badges?.items?[0].badge_image.small ?? string.empty);
}
Update
Maybe like this. I haven't tried it, just a guess:
<DataTemplate>
<Grid DataContext={Binding badges.items}>
<TextBlock Text="{Binding badge_image.small}" />
</Grid>
</DataTemplate>

Related

Entity Framework: get data from many-to-many relationship

I work on an API and when I want to get data from a many-to-many relationship, I get back null.
The connection with the database is OK, and Post date work.
But when I get info from the database, the table for the many-to-many relationship is empty
public class User
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Pseudo { get; set; }
[EmailAddress]
public string Mail { get; set; }
[Required]
public string Pwd { get; set; }
[Required]
public bool IsAdmin { get; set; }
public ICollection<Project> UsersProjectstry { get; set; }
public ICollection<UserProjectMTM> UsersProjects { get; set; }
}
public class Project
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
[MinLength(100)]
public string Description { get; set; }
public string? img { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
[Required]
public int SumGoal { get; set; }
public int Sum { get; set; }
[Required]
public User ProjectManager { get; set; }
public ICollection<UserProjectMTM> Donator { get; set; }
}
public class UserProjectMTM
{
public int PId { get; set; }
public Project Project { get; set; }
public int UId { get; set; }
public User User { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new ProjectConfig());
modelBuilder.ApplyConfiguration(new UserConfig());
modelBuilder.ApplyConfiguration(new CommentConfig());
modelBuilder.Entity<UserProjectMTM>().HasKey(x => new { x.UId, x.PId });
modelBuilder.Entity<UserProjectMTM>().HasOne(p=> p.Project).WithMany(u=> u.Donator).HasForeignKey(x=>x.PId);
modelBuilder.Entity<UserProjectMTM>().HasOne(u => u.User).WithMany(p=> p.UsersProjects).HasForeignKey(x => x.UId);
}
public IEnumerable<TEntity> GetAll()
{
return _Context.Set<TEntity>();
}
public TEntity? GetById(params object[] Id)
{
return _Context.Set<TEntity>().Find(Id);
}
I try a lot of things - so far without success.
I'm junior and I can't find the solution - please help.

Save data on local storage

I am developing an app using Xamarin Forms PCL.
I want to save this class (I use this class as List in code)
public class TagInformation {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
public bool isJob { get; set; }
public string _color { get; set; }
[Ignore]
public Color color { get; set; }
[Ignore]
public JobInformation jobInformation { get; set; }
public TagInformation(Color c, string n) {
color = c;
_color = c.ToHex();
name = n;
isJob = false;
}
public TagInformation() {
}
public void setColor() {
color = Color.FromHex(_color);
}
}
public class JobInformation {
public string shopName { get; set; }
public int wage { get; set; }
public bool isHoliday { get; set; }
public int holidayWage { get; set; }
public bool isMid { get; set; }
public int midnightWage { get; set; }
public bool[] holidayFlgs { get; set; }
public DateTime midStart { get; set; }
public DateTime midEnd { get; set; }
public int tranceportCost { get; set; }
public int closeDay { get; set; }
public int payMentDay { get; set; }
public TimeSpan shortRest { get; set; }
public TimeSpan longRest { get; set; }
public TimeSpan shortRestTime { get; set; }
public TimeSpan longRestTime { get; set; }
public TimeSpan commuteTime { get; set; }
public JobInformation() {
/* do samething */
}
}
Using SQLite, this class has another class, so it doesn't work on.
Is there any other way?
Do you have any ideas?
You could try to use Xamarin.Essentials: Preferences to save it as a json string.
1.Install the Newtonsoft.Json nuget.
2.Serialize your class to json string and save it with a key.
TagInformation tarinformation = xxxxx;
string jsonString = JsonConvert.SerializeObject(tarinformation);
Preferences.Set("your_key", jsonString); //save the data
3.Retrieve a value from preferences and deserialize the string.
var myValue = Preferences.Get("my_key", "default_value");//get the data string
TagInformation infor = JsonConvert.DeserializeObject<TagInformation>(myValue); //deserialize to your class

Missing type map configuration or unsupported mapping.for Collection of DTO

I was making an API for saving a model where it has one to many relationship with another model. When I applying automapping in it. it is giving me following error:
CreateContestDto -> Contest
tritronAPI.DTOs.CreateContestDto -> tritronAPI.Model.Contest
Type Map configuration:
CreateContestDto -> Contest
tritronAPI.DTOs.CreateContestDto -> tritronAPI.Model.Contest
Destination Member:
Problems
---> AutoMapper.AutoMapperMappingException: Missing type map
configuration or unsupported mapping.
Mapping types:
ProblemDto -> Problem
tritronAPI.DTOs.ProblemDto -> tritronAPI.Model.Problem
at lambda_method(Closure , ProblemDto , Problem , ResolutionContext )
My models are: Contest and Problem a contest contain many problems:
public class Contest
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public ICollection<Problem> Problems { get; set; }
public ICollection<ContestProgrammingLanguage>
ContestProgrammingLanguages { get; set; }
}
public class Problem
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string ProblemName { get; set; }
[ForeignKey("User")]
public string ProblemAuthorId { get; set; }
public virtual User ProblemAuthor { get; set; }
public string AuthorName { get; set; }
//public virtual List<Resources> Resourceses { get; set; }
public string ProblemDescription { get; set; }
public bool IsPublished { get; set; }
public virtual ICollection<Submission> Submissions { get; set; }
public string Tags { get; set; }
//public Guid Contest_Id { get; set; }
public virtual Contest Contest { get; set; }
[ForeignKey("Contest")]
public int? Contest_Id { get; set; }
public short Score { get; set; }
//Timelimit in miliseconds
public int TimeLimit { get; set; }
//MemoryLimit in bytes
public int MemoryLimit { get; set; }
//More than source code limit is not allowed
public int? SourceCodeLimit { get; set; }
public virtual ICollection<TestFile> TestFiles { get; set; } = new
List<TestFile>();
}
public class CreateContestDto
{
public CreateContestDto()
{
this.Problems = new HashSet<ProblemDto>();
}
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndDate { get; set; }
public DateTime EndTime { get; set; }
public string BackgroundImage { get; set; }
public string Description { get; set; }
public ICollection<ProblemDto> Problems { get; set; }
}
public class ProblemDto
{
public int Id { get; set; }
public string ProblemName { get; set; }
}
mapping profile:
CreateMap<CreateContestDto, Contest>().ForMember(
dest => dest.Problems , opt => opt.MapFrom(src =>
src.Problems));
controller code:
public async Task<IActionResult> AddContest([FromBody]
CreateContestDto contest)
{
var con = _mapper.Map<Contest>(contest);
this._uow.ContestRepository.Add(con);
return Ok();
}
I have already tried with reversemap selecting new id in mapping profile
You also need to add mappings for ProblemDTO to Problem:
CreateMap<CreateContestDto, Contest>();
CreateMap<ProblemDto, Problem>();

Entity Framework Parent\Child Retrieval

I have an ID of a "Component" parent record that I need to retrieve all the "Attachment" child records. The grid I am using need fields returned an placed in "TheComponentAttachmentsJoinedTable" I am only able to retrieve one record. I have used the value of FirstorDefault. That is the only way it will accept the line of code without complaining about the IEnumerable to int. Could someone please explain what is incorrect?
public class Component
{
public int ID { get; set; }
public string ComponentCode { get; set; }
public string ComponentDescription { get; set; }
public double ComponentWeight { get; set; }
public double ComponentQuantity { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
public virtual ICollection<Attachment> Attachments { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Element> Elements { get; set; }
}
public class Attachment
{
public int ID { get; set; }
public string AttachmentDescription { get; set; }
public string OriginalName { get; set; }
public string MimeType { get; set; }
public byte[] bytes { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
//Navigation
public virtual ICollection<Element> Elements { get; set; }
public virtual ICollection<Component> Components { get; set; } //lt M-m
}
public class TheComponentAttachmentsJoinedTable
{
public int ComponentID { get; set; }
public int AttachmentID { get; set; }
public string OriginalName { get; set; }
}
public static List<TheComponentAttachmentsJoinedTable> ComponentAttachments_GetAllByComponentID(int ComponentID)
{
using (TheContext TheDB = new TheContext())
{
var r = (from x in TheDB.Component
.Where(x => x.ID == ComponentID)
.Include(x => x.Attachments)
select new TheComponentAttachmentsJoinedTable
{
ComponentID = x.ID,
AttachmentID = x.Attachments.Select(y => (y.ID)).FirstOrDefault(),
OriginalName = x.Attachments.Select(y => y.OriginalName).FirstOrDefault().ToString(),
}
);
return r.ToList();
}

WCF cannot implement interface - no matching return type

Why do I get this error:
Error 1 'JoomlaWebservice.KundeService' does not implement interface
member 'JoomlaWebservice.ServiceInterface.HentOpgave(int)'.
'JoomlaWebservice.KundeService.HentOpgave(int)' cannot implement
'JoomlaWebservice.ServiceInterface.HentOpgave(int)' because it does
not have the matching return type of
'JoomlaWebservice.Opgave'. C:\Visual Studio
2010\Projects\JoomlaWebservice\JoomlaWebservice\KundeService.svc.cs 12 18 JoomlaWebservice
Code (Service):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JoomlaWebservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class KundeService : ServiceInterface
{
LIMSEntities LimsEntities;
public class OpgaveOverskrift
{
public int id { get; set; }
public string nummer { get; set; }
public string sagsnavn { get; set; }
public string sagsnr { get; set; }
public string matrix { get; set; }
public string status { get; set; }
}
public class Opgave
{
public int id { get; set; }
public string nummer { get; set; }
public string sagsnavn { get; set; }
public string sagsnr { get; set; }
public string journalnr { get; set; }
public string omnummer { get; set; }
public string matrix { get; set; }
public string status { get; set; }
public string anlaeg { get; set; }
public string anlaeg_kode2 { get; set; }
public bool akkrediteret { get; set; }
public string modtagdato { get; set; }
public string analysedato { get; set; }
public string rapportdato { get; set; }
public int antalproever { get; set; }
public string preopbevar { get; set; }
public int antalbilag { get; set; }
public string rapportnoter { get; set; }
public string afssagsbehandler_navn { get; set; }
public string afssagsbehandler_titel { get; set; }
public string hmansvarlig_navn { get; set; }
public string hmansvarlig_titel { get; set; }
public string kontakt { get; set; } //k0_kontakt01
public string afdeling { get; set; }
public string adresse { get; set; }
public string nation { get; set; }
public string postnummer { get; set; }
public string distrikt { get; set; }
public string postdist { get; set; } //std00002
}
public class Parameter
{
public int id { get; set; }
public int o1id { get; set; }
public string minimum { get; set; }
public string vejledende { get; set; }
public string maksimum { get; set; }
public string bemaerkning { get; set; }
public string parameter { get; set; }
public int metoderf { get; set; }
public int raekkefoelge { get; set; }
public string enhed { get; set; }
public string metoderef { get; set; }
public string detektionsgraense { get; set; }
public string nedremaalegraense { get; set; }
public string oevremaalegraense { get; set; }
public string knaek { get; set; }
public string nedreusikkerhedabs { get; set; }
public string nedreusikkerhedrel { get; set; }
public string oevreusikkerhedabs { get; set; }
public string oevreusikkerhedrel { get; set; }
public string resultat { get; set; }
public int a0id { get; set; }
public bool akkrediteret { get; set; }
public string analysested { get; set; }
public string kommentar { get; set; }
public int laboratorieid { get; set; } //a_internmetode
public string danakkode { get; set; } //k0_kontakt01
}
public List<Parameter> Parametre(int o1id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O2_Parameter01
where i.O1ID == o1id
select new Parameter()
{
a0id = i.A0ID.HasValue ? (int)i.A0ID : 0,
akkrediteret = i.Akkrediteret.HasValue ? (bool)i.Akkrediteret : false,
analysested = i.AnalyseSted,
bemaerkning = i.Bemærkning,
detektionsgraense = i.Detektionsgrænse,
enhed = i.Enhed,
id = i.ID,
knaek = i.Knæk,
kommentar = i.Kommentar,
maksimum = i.Maksimum,
metoderef = i.Metoderef,
metoderf = i.MetodeRf.HasValue ? (int)i.MetodeRf : 1,
minimum = i.Minimum,
nedremaalegraense = i.NedreMålegrænse,
nedreusikkerhedabs = i.NedreUsikkerhedAbs,
nedreusikkerhedrel = i.NedreUsikkerhedRel,
o1id = i.O1ID,
oevremaalegraense = i.ØvreMålegrænse,
oevreusikkerhedabs = i.ØvreUsikkerhedAbs,
oevreusikkerhedrel = i.ØvreUsikkerhedRel,
parameter = i.Parameter,
raekkefoelge = i.Rækkefølge.HasValue ? (int)i.Rækkefølge : 1,
resultat = i.Resultat,
vejledende = i.VejledendeVærdi,
laboratorieid = i.ParameterIAnalyser.A_InternMetode.K0ID.HasValue ? (int)i.ParameterIAnalyser.A_InternMetode.K0ID : 0,
danakkode = i.ParameterIAnalyser.A_InternMetode.K0_Kontakt01.DANAKkode
}).ToList();
}
}
public class Proeve
{
public int id { get; set; }
public int o0id { get; set; }
public string omfang { get; set; }
public string formaal { get; set; }
public string proevetager { get; set; }
public string udtagdatostart { get; set; }
public string udtagdatoslut { get; set; }
public string dybde { get; set; }
public string proeveid { get; set; }
public string abtekst { get; set; } //ab_formål
}
public List<Proeve> Proever(int o0id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O1_Prøve
join f in LimsEntities.AB_Formål on i.Formål equals f.ID.ToString() into fs
from f in fs.DefaultIfEmpty()
where i.O0ID == o0id
select new Proeve()
{
id = i.ID,
o0id = i.O0ID,
omfang = i.Omfang,
formaal = i.Formål,
proevetager = i.Prøvetager,
udtagdatostart = i.UdtagDatoStart,
udtagdatoslut = i.UdtagDatoSlut,
dybde = i.Dybde,
proeveid = i.PrøveID,
abtekst = f == null ? "" : f.Tekst
}).ToList();
}
}
public int Login(String username, String password)
{
LimsEntities = new LIMSEntities();
IEnumerable<K1_Kontaktperson01> kontakter = from k in LimsEntities.K1_Kontaktperson01
where k.HSBrugernavn == username && k.HSAdgangskode == password
select k;
return kontakter.FirstOrDefault().K0ID;
}
public List<OpgaveOverskrift> OpgaveOverskrifter(int k0id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O0_Opgave01
where i.K0ID == k0id
select new OpgaveOverskrift()
{
id = i.ID,
nummer = i.Nummer,
sagsnavn = i.Sagsnavn,
sagsnr = i.SagsNr,
matrix = i.Matrix,
status = i.Status
}).ToList();
}
}
public Opgave HentOpgave(int o0id)
{
/* Opgave test = new Opgave();
return test;*/
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O0_Opgave01
where i.ID == o0id
select new Opgave()
{
id = i.ID,
nummer = i.Nummer,
sagsnavn = i.Sagsnavn,
sagsnr = i.SagsNr,
matrix = i.Matrix,
journalnr = i.JournalNr,
omnummer = i.OMNummer,
status = i.Status,
anlaeg = i.Anlæg,
anlaeg_kode2 = i.Anlæg_Kode2,
akkrediteret = i.Akkrediteret,
modtagdato = i.ModtagDato,
analysedato = i.AnalyseDato,
rapportdato = i.RapportDato,
antalproever = i.AntalPrøver.HasValue ? (int)i.AntalPrøver.Value : 0,
preopbevar = i.PreOpbevar,
antalbilag = i.AntalBilag.HasValue ? (int)i.AntalBilag.Value : 0,
rapportnoter = i.RapportNoter,
afssagsbehandler_navn = i.AFSSagsbehandler_Navn,
afssagsbehandler_titel = i.AFSSagsbehandler_Titel,
hmansvarlig_navn = i.HMAnsvarlig_Navn,
hmansvarlig_titel = i.HMAnsvarlig_Titel,
kontakt = i.K0_Kontakt01.Kontakt,
afdeling = i.K0_Kontakt01.Afdeling,
adresse = i.K0_Kontakt01.Adresse,
nation = i.K0_Kontakt01.Nation,
postnummer = i.K0_Kontakt01.Postnummer,
distrikt = i.K0_Kontakt01.Distrikt,
postdist = i.K0_Kontakt01.std00002.postdist
}).FirstOrDefault();
}
}
}
}
Code (Interface):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JoomlaWebservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ServiceInterface
{
[OperationContract]
int Login(String username, String password);
[OperationContract]
Opgave HentOpgave(int o0id);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class OpgaveOverskrift
{
[DataMember]
public int id { get; set; }
[DataMember]
public string sagsnavn { get; set; }
[DataMember]
public string sagsnr { get; set; }
[DataMember]
public string matrix { get; set; }
[DataMember]
public string status { get; set; }
}
[DataContract]
public class Opgave
{
[DataMember]
public int id { get; set; }
[DataMember]
public string nummer { get; set; }
[DataMember]
public string sagsnavn { get; set; }
[DataMember]
public string sagsnr { get; set; }
[DataMember]
public string journalnr { get; set; }
[DataMember]
public string omnummer { get; set; }
[DataMember]
public string matrix { get; set; }
[DataMember]
public string status { get; set; }
[DataMember]
public string anlaeg { get; set; }
[DataMember]
public string anlaeg_kode2 { get; set; }
[DataMember]
public bool akkrediteret { get; set; }
[DataMember]
public string modtagdato { get; set; }
[DataMember]
public string analysedato { get; set; }
[DataMember]
public string rapportdato { get; set; }
[DataMember]
public int antalproever { get; set; }
[DataMember]
public string preopbevar { get; set; }
[DataMember]
public int antalbilag { get; set; }
[DataMember]
public string rapportnoter { get; set; }
[DataMember]
public string afssagsbehandler_navn { get; set; }
[DataMember]
public string afssagsbehandler_titel { get; set; }
[DataMember]
public string hmansvarlig_navn { get; set; }
[DataMember]
public string hmansvarlig_titel { get; set; }
[DataMember]
public string kontakt { get; set; } //k0_kontakt01
[DataMember]
public string afdeling { get; set; }
[DataMember]
public string adresse { get; set; }
[DataMember]
public string nation { get; set; }
[DataMember]
public string postnummer { get; set; }
[DataMember]
public string distrikt { get; set; }
[DataMember]
public string postdist { get; set; } //std00002
}
[DataContract]
public class Proeve
{
[DataMember]
public int id { get; set; }
[DataMember]
public int o0id { get; set; }
[DataMember]
public string omfang { get; set; }
[DataMember]
public string formaal { get; set; }
[DataMember]
public string proevetager { get; set; }
[DataMember]
public string udtagdatostart { get; set; }
[DataMember]
public string udtagdatoslut { get; set; }
[DataMember]
public string dybde { get; set; }
[DataMember]
public string proeveid { get; set; }
[DataMember]
public string abtekst { get; set; } //ab_formål
}
[DataContract]
public class Parameter
{
[DataMember]
public int id { get; set; }
[DataMember]
public int o1id { get; set; }
[DataMember]
public string minimum { get; set; }
[DataMember]
public string vejledende { get; set; }
[DataMember]
public string maksimum { get; set; }
[DataMember]
public string bemaerkning { get; set; }
[DataMember]
public string parameter { get; set; }
[DataMember]
public int metoderf { get; set; }
[DataMember]
public int raekkefoelge { get; set; }
[DataMember]
public string enhed { get; set; }
[DataMember]
public string metoderef { get; set; }
[DataMember]
public string detektionsgraense { get; set; }
[DataMember]
public string nedremaalegraense { get; set; }
[DataMember]
public string oevremaalegraense { get; set; }
[DataMember]
public string knaek { get; set; }
[DataMember]
public string nedreusikkerhedabs { get; set; }
[DataMember]
public string nedreusikkerhedrel { get; set; }
[DataMember]
public string oevreusikkerhedabs { get; set; }
[DataMember]
public string oevreusikkerhedrel { get; set; }
[DataMember]
public string resultat { get; set; }
[DataMember]
public int a0id { get; set; }
[DataMember]
public bool akkrediteret { get; set; }
[DataMember]
public string analysested { get; set; }
[DataMember]
public string kommentar { get; set; }
[DataMember]
public int laboratorieid { get; set; } //a_internmetode
[DataMember]
public string danakkode { get; set; } //k0_kontakt01
}
}
You're returning JoomlaWebservice.KundeService.Opgave, not JoomlaWebservice.Opgave. You need to change your code to either return the contract directly or to map between your created object and the contract.