EF Core - Single Selection of child collection stored at parent

c# entity-framework-core

Question

Working with .NET Core 3.0 and EF Core if that impacts things.

I'm trying to define a model where:

  • A user owns a collection of toys.
  • A user can have a currently selected toy.

I'm trying to model this as such (BaseModel has common properties to all my entities), and AVUser is my ASP.NET Identity user class.

public abstract class BaseModel
{
    public int Id { get; set; }
    public DateTime LastModifiedDate { get; set; }
    public DateTime CreatedDate { get; set; }
    public AVUser CreatedUser { get; set; }
    public AVUser ModifiedUser { get; set; }
}

public class Toy: BaseModel
{
    [MaxLength(80)]
    public string Name { get; set; }

}

public class AVUser : IdentityUser
{
    public string FirstName { get; set; }

    // The currently selected toy for the user.
    public int SelectedToyId { get; set; }
    public Toy SelectedToy { get; set; }

}

However, EF Core throws an error stating: Unable to determine the relationship represented by navigation property 'AVUser.Toy' of type 'Toy'.

I am having trouble how I annotate this so it knows that the user can have a collection of toys, and I want to store a single toy with the user as the currently selected one.

1
0
2/6/2019 5:21:12 PM

Accepted Answer

Write your model classes as follows:

public class Toy: BaseModel
{
    [MaxLength(80)]
    public string Name { get; set; }

    [ForeignKey("AVUser")]
    public string UserId { get; set; }

    public AVUser AVUser { get; set; }

}

public class AVUser : IdentityUser
{
    public string FirstName { get; set; }

    // The currently selected toy for the user.
    [ForeignKey("SelectedToy")]
    public int SelectedToyId { get; set; }
    public Toy SelectedToy { get; set; }

    public ICollection<Toy> Toys {get; set;}

}

Then configure in the OnModelCreating in DbContext as follows:

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
      base.OnModelCreating(modelBuilder);

      modelBuilder.Entity<AVUser>().HasOne(a => a.SelectedToy).WithOne();
      modelBuilder.Entity<AVUser>().HasMany(a => a.Toys).WithOne(t => t.AVUser).HasForeignKey(t => t.UserId);
 }
2
2/6/2019 5:37:31 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