Search code examples
c#entity

C# Entity Foreign Key to List Array


I have a class PromoCard and List<PromoCard> PromoCards. Is it possible to map element of List array in Entity Model?

This is my List:

public static List<PromoCard> PromoCards = new List<PromoCard>
{
    new PromoCard()
    {
        Id = 1,
        Crystal = 4500,
        Price = 100
    },
    new PromoCard()
    {
        Id = 2,
        Crystal = 24000,
        Price = 500
    },
    new PromoCard()
    {
        Id = 3,
        Crystal = 50000,
        Price = 1000
    },
};

public class PromoCard
{
    [Key]
    public int Id { get; set; }
    public int Crystal { get; set; }
    public int Price { get; set; }
}

And this is my model:

public class BonusCard
{
    [Key]
    public int Id { get; set; }
    public string User_id { get; set; }
    [ForeignKey("User_id")]
    public virtual ApplicationUser User { get; set; }
    public int PromoCard_id { get; set; }
    // is there way to link 
    [ForeignKey("PromoCard_id")]
    public virtual PromoCard PromoCard { get; set; }
}

Solution

  • All I had to was change the getter of PromoCard property and put NotMapped Annotation on it

    public class BonusCard
    {
    
        [Key]
        public int Id { get; set; }
        public string User_id { get; set; }
        [ForeignKey("User_id")]
        public virtual ApplicationUser User { get; set; }
        public string Code { get; set; }
        public DateTime CreationDate { get; set; } = (DateTime)SqlDateTime.MinValue;
        public DateTime UsageDate { get; set; } = (DateTime)SqlDateTime.MinValue;
        public int? Player_id { get; set; } = null;
        [ForeignKey("Player_id")]
        public virtual Player Player { get; set; }
        public int PromoCard_id { get; set; }
        [NotMapped]
        public  PromoCard PromoCard { get { return PromoCards[PromoCard_id]; } set { } }
    }