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.
Related
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>();
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>
This is my error :
Unable to determine the principal end of an association between the types 'SANTEK.Web.Models.SantekOrder' and 'SANTEK.Web.Models.OrderMoneySum'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
What is my mistake logically ?? I mean to build one-to-one relation.
My model classes are here :
[Table("Orders")]
public class SantekOrder
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SantekOrderId { get; set; }
[Required, StringLength(25)]
[DisplayName("Çatdırılacaq şəxs")]
public string DelivaryManName { get; set; }
[DisplayName("Çatdırılacaq şəxs istifadəçidir?")]
public bool DeliveryManIsUser { get; set; }
[Required, StringLength(25)]
[DisplayName("Çatdırılacaq şəxs ad və soyadı")]
public string DelivaryManSurname { get; set; }
[Required, StringLength(10)]
[DisplayName("Çatdırılacaq şəxs tefon nömrəsi")]
public string DelivaryManTel { get; set; }
[DisplayName("Çatdırılacaq ünvan istifadəçinin ünvandır?")]
public bool IsUserAddress { get; set; }
[Required, StringLength(150)]
[DisplayName("Çatdırılacaq şəxsin ünvanı?")]
public string DelivaryManAddress { get; set; }
public int SanTekUserId { get; set; }
public int OrderMoneySumId { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy-hh-mm-ss}",
ApplyFormatInEditMode = true)]
public DateTime Time { get; set; }
[ForeignKey("SanTekUserId")]
public virtual SanTekUser SanUser { get; set; }
[ForeignKey("SanTekUserId")]
public virtual OrderMoneySum OrderMoneySum { get; set; }
}
This is my OrdersDetail Table to hold all product and their quantity
[Table("OrderedProducts")]
public class OrderMoneySum
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OrderMoneySumId { get; set; }
[Required]
public int SantekOrderId { get; set; }
[Required]
public int AllProductId { get; set; }
[DisplayName("Miqdarı")]
public int Quantity { get; set; }
[ForeignKey("SantekOrderId")]
public virtual SantekOrder SantekOrder { get; set; }
[ForeignKey("SantekOrderId")]
public virtual AllProduct AllProduct { get; set; }
}
I'm still new in creating Models using Entity Framework and MVC 4 Razor. I'm having a problem on how can I save a history of a model. How can I create a model that have a history on specific tables or fields ? For ex: If I wish to create a history on the changes on the school. Its still not clear to me how will I I create the model that saves history. How will be the triggering do I have to execute the save function on different models with the same data ?
Thank you so much in advance.
If anyone could be a simple example of model and a model history and how it is functioning, I'll be very grateful. Like a Sales or sales history.
Here's my code
One To Many
public class Child
{
[Key]
public int ChildID { get; set; }
[Required,Display(Name="Project Code")]
public string ProjectCode { get; set; }
public string Status { get; set; }
[DataType(DataType.Date)]
public DateTime StatusDate { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
public string Gender {get;set;}
public string Address { get; set; }
public string Section { get; set; }
public int SchoolLevelID { get; set; }
public int SchoolYearID { get; set; }
public int AreaID { get; set; }
public int SchoolID { get; set; }
public int GradeLevelID { get; set; }
//Foreign Key - One to Many
public virtual SchoolLevel SchoolLevel { get; set; }
public virtual SchoolYear SchoolYear { get; set; }
public virtual Area Area { get; set; }
public virtual School School { get; set; }
public virtual GradeLevel GradeLevel{get;set;}
//Child is foreign key at the table
public virtual ICollection<Guardian> Guardians { get; set; }
}
public class SchoolLevel
{
public int SchoolLevelID { get; set; }
public string SchoolLevelName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class SchoolYear
{
public int SchoolYearID { get; set; }
public string SchoolYearName { get; set; }
public virtual ICollection<Child> Children{get;set;}
}
public class Area
{
public int AreaID{get;set;}
public string AreaName { get; set; }
public virtual ICollection<Child> Children{get;set;}
}
public class School
{
public int SchoolID { get; set; }
public string SchoolName{get;set;}
public virtual ICollection<Child> Children { get; set; }
}
public class GradeLevel
{
public int GradeLevelID{get;set;}
public string GradeLevelName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class ChildDbContext : DbContext
{
public DbSet<Child> Children { get; set; }
public DbSet<SchoolLevel> SchoolLevels { get; set; }
public DbSet<SchoolYear> SchoolYears { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<School> Schools { get; set; }
public DbSet<GradeLevel> GradeLevels { get; set; }
public DbSet<Guardian> Guardians { get; set; }
}
You can use this approach: Create a History model. That contains 1 changeness like o log.
public class History
{
public int HistoryId { get; set; }
public int ModelType { get; set; } //it is ModelTypeEnum value.
public int ModelId { get; set; }
public string PropertyName { get; set; }
public string Propertyvalue {get;set;}
public DateTime ChangeDate { get; set; }
public int ChangedUserId { get; set; }
}
And Enum:
public enum ModelTypeEnum
{
Child =1,
SchoolLevel = 2,
//etc..
};
For example, when you edit 1 Child entity, give changed properties name and value, it's id, type and others (ChangeDate, ChangedUserId) to History and save histories. If 3 properties will change you should save 3 history entities. Then, you can load (filter) histories by ModelId, by ChangedUserId etc.
I a am new to entity framework. I have created project with Entity Model. When i am trying to add item in to the table it gives error "Multiplicity Constraint violated" Any idea?
ID From Table MAPPER is FK in MAPS table.
In Code Behind:
private Mapper mMapper;
if (mMapper.Id == 0)
db.Mappers.Add(mMapper);
db.SaveChanges();
public partial class Mapper
{
public Mapper()
{
this.Maps = new HashSet<Map>();
}
public int Id { get; set; }
public string Name { get; set; }
public string RecordDelimiter { get; set; }
public string ValueDelimiter { get; set; }
public Nullable<int> ColumnDescriptionRow { get; set; }
public Nullable<int> FirstRowOfData { get; set; }
public Nullable<bool> IgnoreThisRecord { get; set; }
public Nullable<bool> ExplodePartQuantity { get; set; }
public Nullable<bool> IgnoreImportingErrors { get; set; }
public Nullable<int> AngleMappingLeadingEdgeId { get; set; }
public Nullable<int> AngleMappingTrailingEdgeId { get; set; }
public string ValueWrapper { get; set; }
public string ValueWrapperDelimiter { get; set; }
public virtual AngleMapping AngleMapping { get; set; }
public virtual AngleMapping AngleMapping1 { get; set; }
public virtual ICollection<Map> Maps { get; set; }
}
Help Appreciated!