EF Core Populate a "NotMapped property" from a not included List of entities

c# entity-framework-core

Question

I have two entities like these

    public class PetShop
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public IList<Cat> Cats { get; set; }

        [NotMapped]
        public Cat OldestCat {
            get => Cats.OrderBy(c => c.BirthDate).FirstOrDefault();
        }
    }

    public class Cat
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }
    }

Normally to get the PetShop with all the cats, this is the query I have to make with my DbContext:

    DbContext
        .PetShop
        .Include(a => a.Cats);

But sometimes I do not want to include all the cats of my PetShops, since I could have a lot of cats, but I still need to populate my OldestCat, but without including the cats, my getter will return me nothing.

Is there a way to populate my NotMapped OldestCat property without including all my cats ?

1
0
2/20/2020 5:01:47 PM

Popular Answer

Edit. I changed the answer. Mabye the easiest would be to make a link from cat to petshop and then begin with the Cat and from that Select the petshop?

I have not tested the code.

DbContext
.Cats
.Where(c => c.PetShop.Id == 5)
.OrderBy(c => c.BirthDate)
.Select(c => c.PetShop)
.FirstOrDefault()
0
2/21/2020 2:32:52 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