Home > Enterprise >  ASP.Net core - make a search inside a nested collection
ASP.Net core - make a search inside a nested collection

Time:11-08

I'm trying to make a nested collection search and I'm really struggling.

My expected result is: I would like to make a search and find all the powerUp objects by a certain date. (PowerUpDate property - that's the searching criteria)

User Model:

public class AppUser : IdentityUser
{
    public ICollection<Hero> Heroes { get; set; }
}

Hero Model:

[Table("Heroes")]
public class Hero
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Ability { get; set; }

    [Required]
    public string SuitColors { get; set; }
    public double CurrentPower { get; set; }
    public double StartingPower { get; set; }
    public DateTime Created { get; set; } = DateTime.Now;
    public ICollection<PowerUp> PowerUps { get; set; }
    public AppUser AppUser { get; set; }

    [Required]
    public string AppUserId { get; set; }
}

PowerUp Model:

[Table("PowerUps")]
public class PowerUp
{
    public int Id { get; set; }

    [Required]
    public double PowerUpIncrement { get; set; }

    [Required]
    public DateTime PowerUpDate { get; set; } = DateTime.Now;
    public Hero Hero { get; set; }

    [Required]
    public int HeroId { get; set; }
}

DataContext:

public class DataContext : IdentityDbContext<AppUser>
{
    public DataContext(DbContextOptions options) : base(options)
    {

    }

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

        builder.Entity<Hero>().HasMany(hero => hero.PowerUps).WithOne(powerUp => powerUp.Hero)
            .OnDelete(DeleteBehavior.Cascade);

        builder.Entity<AppUser>().HasMany(user => user.Heroes).WithOne(hero => hero.AppUser)
            .OnDelete(DeleteBehavior.Cascade);

    }
}

Could someone please explain to me how can I implement such a search on a nested collection?

CodePudding user response:

Inject your AppUser user using Dependency injection (better use the repository pattern) anyway it should be something like this: user.Heroes.PowerUps.OrderBy(x=>x.PowerUpDate == Datetime.Now).ToList();

x.PowerUpDate == To whatever date you will insert

  • Related