2 many to many relationship between 2 classes - c#

public class LootItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Ilvl { get; set; }
public ItemSlot slot { get; set; }
public virtual ICollection<LootPlayer> Player { get; set; }
public virtual ICollection<LootPlayer> PlayerBis { get; set; }
public LootItem()
{
Player = new List<LootPlayer>();
PlayerBis = new List<LootPlayer>();
}
}
public class LootPlayer
{
public int Id { get; set; }
public string Name { get; set; }
public LootClass PlayerClass { get; set; }
public LootRole PlayerRole { get; set; }
public virtual ICollection<LootItem> CurrentGear { get; set; }
public virtual ICollection<LootItem> BisGear { get; set; }
public LootPlayer()
{
CurrentGear = new List<LootItem>();
BisGear = new List<LootItem>();
}
}
I'm trying to create 2 x many to many relations between these 2 tables.
Player <-> CurrentGear
PlayerBis <-> BisGear
Is this posible, because currently when I run the Update-Database I don't get any relationship tables. Only LootItem and LootPlayer

You Can't create many-to-many relationship. you should create two one-to-many relationship like this. create an class like this
public class LootPlayerLootItem
{
public int Id { get; set; }
public int PlayerId { get; set; }
public int PlayerBisId { get; set; }
public int CurrentGearId { get; set; }
public int BisGearId { get; set; }
[ForeignKey("CurrentGearId")]
public LootPlayer CurrentGear { get; set; }
[ForeignKey("BisGearId")]
public LootPlayer BisGear { get; set; }
[ForeignKey("PlayerId")]
public LootItem Player { get; set; }
[ForeignKey("PlayerBisId")]
public LootItem PlayerBis { get; set; }
}
then change the LootItem and LootPlayer to this
public class LootItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Ilvl { get; set; }
public ItemSlot slot { get; set; }
[InverseProperty("Player")]
public virtual ICollection<LootPlayerLootItem> Player { get; set; }
[InverseProperty("PlayerBis")]
public virtual ICollection<LootPlayerLootItem> PlayerBis { get; set; }
public LootItem()
{
Player = new List<LootPlayerLootItem>();
PlayerBis = new List<LootPlayerLootItem>();
}
}
public class LootPlayer
{
public int Id { get; set; }
public string Name { get; set; }
public LootClass PlayerClass { get; set; }
public LootRole PlayerRole { get; set; }
[InverseProperty("CurrentGear")]
public virtual ICollection<LootPlayerLootItem> CurrentGear { get; set; }
[InverseProperty("BisGear")]
public virtual ICollection<LootPlayerLootItem> BisGear { get; set; }
public LootPlayer()
{
CurrentGear = new List<LootPlayerLootItem>();
BisGear = new List<LootPlayerLootItem>();
}
}

Related

How De-serialize response JSON with dynamic keys?

I know that this question is asked many times but still I'm struggling to understand this. I have below json to c# converted class.
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Accessibility
{
public bool share { get; set; }
public bool comment { get; set; }
}
public class Avatar
{
public string #base { get; set; }
}
public class Beautifulnari
{
public List<Post> posts { get; set; }
public long totalViewsCount { get; set; }
}
public class CaptionSignals
{
public bool safe { get; set; }
public Unsafe #unsafe { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class Count
{
public int likes { get; set; }
public int views { get; set; }
}
public class Datum
{
public Haythandi haythandi { get; set; }
public Beautifulnari beautifulnari { get; set; }
}
public class HashtagDatum
{
public string _id { get; set; }
public string hashTagId { get; set; }
public string hashtagName { get; set; }
}
public class Haythandi
{
public List<Post> posts { get; set; }
public int totalViewsCount { get; set; }
}
public class Loc
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class MediaLocation
{
public int isHLS { get; set; }
public bool isTranscoded { get; set; }
public double duration { get; set; }
public string #base { get; set; }
public string thumbNailPath { get; set; }
public string path { get; set; }
public int mediaType { get; set; }
public string f0 { get; set; }
public string thumbnail { get; set; }
public Transcoded transcoded { get; set; }
public string compressedThumbnailPath { get; set; }
public string oPath { get; set; }
public string resizedThumbnailPath { get; set; }
public Resolution resolution { get; set; }
public Thumbnails thumbnails { get; set; }
public string webPath { get; set; }
}
public class ModerationStatus
{
public int approval { get; set; }
public int payment { get; set; }
public bool isModerated { get; set; }
public string moderatedBy { get; set; }
public string approvedBy { get; set; }
public DateTime? approvalDate { get; set; }
public DateTime? moderationDate { get; set; }
public int isAccepted { get; set; }
public string acceptedBy { get; set; }
public DateTime acceptanceDate { get; set; }
public object hashtagRejectReason { get; set; }
public int isOriginalAudio { get; set; }
public object ogAudioAcceptedBy { get; set; }
public object ogAudioAcceptanceDate { get; set; }
public object ogAudioRejectReason { get; set; }
public string acceptedHashtagId { get; set; }
}
public class ModerationV2Array
{
public string moderatorId { get; set; }
public string moderatorName { get; set; }
public object moderationSignals { get; set; }
public string response { get; set; }
}
public class OwnerData
{
public Avatar avatar { get; set; }
public string _id { get; set; }
public string name { get; set; }
public string username { get; set; }
public string status { get; set; }
public string profilePic { get; set; }
public int isProfileVerified { get; set; }
public int isFollowed { get; set; }
public int tipEnabled { get; set; }
}
public class Post
{
public string _id { get; set; }
public MediaLocation mediaLocation { get; set; }
public TempMedia tempMedia { get; set; }
public Song song { get; set; }
public Count count { get; set; }
public Accessibility accessibility { get; set; }
public OwnerData ownerData { get; set; }
public ModerationStatus moderationStatus { get; set; }
public TaggedStatus taggedStatus { get; set; }
public List<string> etags { get; set; }
public bool isDuplicate { get; set; }
public bool isProcessed { get; set; }
public string caption { get; set; }
public List<string> hashtagIds { get; set; }
public string youtubeLink { get; set; }
public bool isPrivate { get; set; }
public int reportPostsCount { get; set; }
public string audioLang { get; set; }
public object cta_text { get; set; }
public string ip { get; set; }
public string country { get; set; }
public string city { get; set; }
public string versionCode { get; set; }
public string createdBy { get; set; }
public string postType { get; set; }
public string uploadSource { get; set; }
public bool isSpam { get; set; }
public bool isPremium { get; set; }
public int metaProcessed { get; set; }
public int isShoppable { get; set; }
public int isLiked { get; set; }
public bool onlyFollowers { get; set; }
public bool isPrivateByAdmin { get; set; }
public int isPinned { get; set; }
public int isPromoted { get; set; }
public int isMiningAllowed { get; set; }
public string s3RefId { get; set; }
public string userId { get; set; }
public object duplicateOfPostId { get; set; }
public List<HashtagDatum> hashtagData { get; set; }
public List<Category> categories { get; set; }
public string gender { get; set; }
public int shareCount { get; set; }
public int likeCount { get; set; }
public int commentCount { get; set; }
public int viewsCount { get; set; }
public string status { get; set; }
public string language { get; set; }
public string created_at { get; set; }
public List<object> spamReason { get; set; }
public List<object> taggedUsers { get; set; }
public int __v { get; set; }
public Loc loc { get; set; }
public string region { get; set; }
public bool? enableV2 { get; set; }
public List<ModerationV2Array> moderationV2Array { get; set; }
public bool? ignoreV2 { get; set; }
public bool? isPremiumV2 { get; set; }
public bool? isSpamV2 { get; set; }
public List<PremiumCCSignal> premiumCCSignals { get; set; }
}
public class PremiumCCSignal
{
public string moderatorId { get; set; }
public CaptionSignals captionSignals { get; set; }
}
public class Resolution
{
public int width { get; set; }
public int height { get; set; }
}
public class Root
{
public int code { get; set; }
public List<Datum> data { get; set; }
public string message { get; set; }
public bool hasmoreData { get; set; }
public object error { get; set; }
}
public class Song
{
public string _id { get; set; }
public string title { get; set; }
public string art { get; set; }
public string author { get; set; }
public string categoryName { get; set; }
public object albumName { get; set; }
public int startTime { get; set; }
public double endTime { get; set; }
public string acrId { get; set; }
}
public class TaggedStatus
{
public bool isTagged { get; set; }
public string taggedBy { get; set; }
public DateTime taggedDate { get; set; }
}
public class TempMedia
{
public int isHls { get; set; }
}
public class Thumbnails
{
public string w50 { get; set; }
public string w150 { get; set; }
public string w300 { get; set; }
public string w700 { get; set; }
}
public class Transcoded
{
public string p1024 { get; set; }
public string p480 { get; set; }
public string p720 { get; set; }
}
public class Unsafe
{
}
In this above JSON, classes mentioned below are dynamic keys into response JSON.
Haythandi
Beautifulnari
The problem is that values Haythandi and beautifulNari as class name (if convert to c#) which are actually ids of that particular record. How do I convert these id's into c# class?, I have tried multiple approaches like using Dictionaries, JObjects, dynamic and Expando classes but not result. Any help would be much appreciated.
I think you need change one of the 'character classes' to:
public class MyClassWithPosts // was Beautifulnari
{
public List<Post> posts { get; set; }
public long totalViewsCount { get; set; }
}
After that data can become a dictionary (update: a list of dictionaries):
public class Root
{
public int code { get; set; }
public List<Dictionary<string, MyClassWithPosts>> data { get; set; }

Entity Framework cannot insert data

I am making this a school project and I am first time using the Entity Framework so don't be too harsh about it. These are my tables/classes.
public class Database : DbContext
{
public Database() {}
public DbSet<Producer> Producers { get; set; }
public DbSet<Song> Songs { get; set; }
public DbSet<ProducerSong> ProducerGlasbos { get; set; }
}
public class Song
{
public int Id { get; set; }
public string Title { get; set; }
public int Length { get; set; }
public int Views { get; set; }
}
public class Producer
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string name { get; set; }
public string surname { get; set; }
public int birth { get; set; }
}
public class ProducerSong
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public Producer Producer { get; set; }
public Song Songs { get; set; }
public int year { get; set; }
}
When I try to inset new instance of a class into table/database in just crashes and throws error
Data.Glasbas.Add(new Glasba { length = 200, Naslov = "Bolecina", views= 313});
Error screenshot: Look at me
Thanks for helping.
public class Database : DbContext
{
public Database() { }
public DbSet<Producer> Producers { get; set; }
public DbSet<Song> Songs { get; set; }
public DbSet<ProducerSong> ProducerGlasbos { get; set; }
public class ProducerSong
{
[System.ComponentModel.DataAnnotations.Key]
public int ProducerSongID { get; set; }
public Producer Producer { get; set; }
public Song Songs { get; set; }
public int year { get; set; }
}
public class Song
{
[System.ComponentModel.DataAnnotations.Key]
public int Id { get; set; }
public string Title { get; set; }
public int lenght { get; set; }
public int views { get; set; }
//ForeignKey
public int ProducerSongID { get; set; }
public ProducerSong ProducerSong { get; set; }
}
public class Producer
{
[System.ComponentModel.DataAnnotations.Key]
public int Id { get; set; }
public string name { get; set; }
public string surname { get; set; }
public int birth { get; set; }
//ForeignKey
public int ProducerSongID { get; set; }
public ProducerSong ProducerSong { get; set; }
}
}
The problem was in constructors if I used constructors to create objects it just don't work odd but what can you do..

Can a primary key called twice in another table as foreign key using Entity Framework?

How can I use a primary key as a foreign key of another table's in two columns.
public class ResumeSharing
{
[Key]
public int ResumeSharingId { get; set; }
[ForeignKey("AppliedJobs")]
public int AppliedJobId { get; set; }
public virtual AppliedJob AppliedJobs { get; set; }
public bool OwnCompany { get; set; }
[Display(Name = "RecruiterFrom")]
public int RecruiterId { get; set; }
public virtual Recruiter Recruiters { get; set; }
[Display(Name = "RecruiterTo")]
public int RecruiterId { get; set; }
public virtual Recruiter Recruiters { get; set; }
[ForeignKey("Companies")]
public int CompanyId { get; set; }
public virtual Company Companies { get; set; }
public string SharedFiles { get; set; }
}
I want to call RecruiterId twice in this table. How can I do this?
you have to add navigation properties
public class ResumeSharing
{
[Key]
public int ResumeSharingId { get; set; }
[ForeignKey("AppliedJob")]
public int AppliedJobId { get; set; }
public virtual AppliedJob AppliedJob { get; set; }
public bool OwnCompany { get; set; }
[Display(Name = "RecruiterFrom")]
public int RecruiterFromId { get; set; }
[ForeignKey(nameof(RecruiterFromId))]
[InverseProperty("RecruiterFroms")]
public virtual Recruiter RecruiterFrom { get; set; }
[Display(Name = "RecruiterTo")]
public int RecruiterToId { get; set; }
[ForeignKey(nameof(RecruiterToId))]
[InverseProperty("RecruiterTos")]
public virtual Recruiter RecruiterTo { get; set; }
[ForeignKey("Company")]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
public string SharedFiles { get; set; }
}
public class Recruiter
{
[Key]
public int Id { get; set; }
[InverseProperty(nameof(ResumeSharing.RecruiterFrom))]
public virtual ICollection<Recruiter> RecruiterFroms { get; set; }
[InverseProperty(nameof(ResumeSharing.RecruiterTo))]
public virtual ICollection<Recruiter> RecruiterTos { get; set; }
}

Issue With EF Core ThenInclude Against A Collection

I'm running into this compile error when using ThenInclude on a entity. The error is listed below. I can't see anything wrong with the relationships between the two entities. What gives, I'm banging my head against a wall here!
'ICollection<OptionType>' does not contain a definition for 'ProductOption'
and no extension method 'ProductOption' accepting a first argument of type
'ICollection<OptionType>' could be found (are you missing a using directive or
an assembly reference?)
Here are the two entities in question and related code
public async Task<ProductEditor> Edit(Expression<Func<Product, bool>> filter)
{
var product = _repo.Find(filter)
.Include(x=>x.OptionType)
.ThenInclude(x=>x.ProductOption)
public partial class OptionType
{
public OptionType()
{
ProductOption = new HashSet<ProductOption>();
}
public int OptionTypeId { get; set; }
public int ProductId { get; set; }
public string OptionName { get; set; }
public virtual ICollection<ProductOption> ProductOption { get; set; }
public virtual Product Product { get; set; }
}
public partial class ProductOption
{
public int ProductOptionId { get; set; }
public int OptionTypeId { get; set; }
public string OptionValue { get; set; }
public decimal? Price { get; set; }
public bool IsStocked { get; set; }
public virtual OptionType OptionType { get; set; }
}
public partial class Product
{
public Product()
{
EmailLog = new HashSet<EmailLog>();
OptionType = new HashSet<OptionType>();
Order = new HashSet<Order>();
ProductDiscountCode = new HashSet<ProductDiscountCode>();
ProductPaymentMethod = new HashSet<ProductPaymentMethod>();
ProductPhoto = new HashSet<ProductPhoto>();
ProductViewCounter = new HashSet<ProductViewCounter>();
ProductWishList = new HashSet<ProductWishList>();
}
public int ProductId { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
public decimal RetailPrice { get; set; }
public decimal? SalePrice { get; set; }
public decimal ShippingCost { get; set; }
public int UserId { get; set; }
public bool WillShipInternational { get; set; }
public int QuantityTotal { get; set; }
public int QuantitySold { get; set; }
public bool IsActive { get; set; }
public bool IsBold { get; set; }
public bool IsHighlighted { get; set; }
public bool IsFeatured { get; set; }
public int ReturnPolicyId { get; set; }
public int ConditionId { get; set; }
public int StatusId { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? PostedDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual ICollection<EmailLog> EmailLog { get; set; }
public virtual ICollection<OptionType> OptionType { get; set; }
public virtual ICollection<Order> Order { get; set; }
public virtual ICollection<ProductDiscountCode> ProductDiscountCode { get; set; }
public virtual ICollection<ProductPaymentMethod> ProductPaymentMethod { get; set; }
public virtual ICollection<ProductPhoto> ProductPhoto { get; set; }
public virtual ICollection<ProductViewCounter> ProductViewCounter { get; set; }
public virtual ICollection<ProductWishList> ProductWishList { get; set; }
public virtual ProductCategory Category { get; set; }
public virtual ProductCondition Condition { get; set; }
public virtual ProductSystemReturnPolicy ReturnPolicy { get; set; }
public virtual ProductStatus Status { get; set; }
public virtual User User { get; set; }

Trouble using all members in a class. Why can I only use the list?

I have the following class object structure:
public class StatusObj3
{
public int status { get; set; }
public DataObj3 data { get; set; }
}
public class DataObj3
{
public string survey_id { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int custom_variable_count { get; set; }
public List<Custom_VariablesObj> custom_variables { get; set; }
public int language_id { get; set; }
public int num_responses { get; set; }
public int question_count { get; set; }
public string nickname { get; set; }
public TitleObj title { get; set; }
public List<PagesObj> pages { get; set; }
}
public class Custom_VariablesObj
{
public string variable_label { get; set; }
public string question_id { get; set; }
}
public class TitleObj
{
public bool enabled { get; set; }
public string text { get; set; }
}
public class PagesObj
{
string page_id { get; set; }
string heading { get; set; }
string sub_heading { get; set; }
public List<QuestionObj> questions { get; set; }
}
public class QuestionObj
{
public string question_id { get; set; }
public string heading { get; set; }
public string position { get; set; }
public QuestionTypeObj type { get; set; }
public List<AnswerObj> answers { get; set; }
}
public class QuestionTypeObj
{
public string family { get; set; }
public string subtype { get; set; }
}
public class AnswerObj
{
public string answer_id { get; set; }
public int position { get; set; }
public string text { get; set; }
public string type { get; set; }
public bool visible { get; set; }
public int weight { get; set; }
public bool apply_all_rows { get; set; }
public bool is_answer { get; set; }
public List<ItemsObj> items { get; set; }
}
public class ItemsObj
{
public string answer_id { get; set; }
public int position { get; set; }
public string type { get; set; }
public string text { get; set; }
}
I 've deserialized json into this object via:
var results_SurveyDetails = deserializer.Deserialize<StatusObj3>(json_returned);
I'm trying to loop thru the pages by:
foreach (var page in results_SurveyDetails.data.pages)
However, not all members of page are available to use.
Only the page.questions is there and not page_id, heading and subheading.
What am I doing wrong?
You are missing public on your other properties in class PagesObj.

Categories

Resources