Entity Framework .Core treating foreign key as a primary key

entity-framework-core

Question

I have the two classes shown below. When trying to insert two HeroEntry with the same IdentityId, the context is only saving one of the two entries. Any ideas what I am doing wrong?

public class Identity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int IdentityId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    [JsonIgnore]
    public virtual HeroEntry HeroEntry { get; set; }
}

public class HeroEntry
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int HeroEntryId { get; set; }
    public int IdentityId { get; set; }
    public SuperHeroEnum HeroType { get; set; }
    public DateTime Startdate { get; set; }
    public DateTime EndDate { get; set; }

    [ForeignKey("IdentityId")]
    public virtual Identity Identity { get; set; }
    public virtual List<SuperHeroBreak> SuperHeroBreaks { get; set; }
}

Add code:

var b = new HeroEntry()
            {
                HeroType = SuperHeroEnum.BATMAN,
                Startdate = DateTime.Parse("12/24/2018"),
                EndDate = DateTime.Parse("01/04/2019"),
                IdentityId = 1,
            };

var r = new HeroEntry()
            {
                HeroType = SuperHeroEnum.ROBIN,
                Startdate = DateTime.Parse("12/24/2018"),
                EndDate = DateTime.Parse("01/04/2019"),
                IdentityId = 1,
            };

context.SuperHeroes.AddRange(b, r);

var affected = context.SaveChanges();
1
0
9/7/2018 3:59:55 PM

Popular Answer

Cristian was correct. Adding the navigation property to the identity class solved my issue. Thank you for the help!

0
9/7/2018 8:03:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow