I have a Pets class:
public class Pets {
[Key]
public int Id { get; set; }
public List<int> DogIds { get; set; }
public virtual List<Dog> Dogs { get; set; }
}
I then have a Dog class:
public class Dog {
int Id { get; set; }
// Whatever else
}
what I would like to be able to do is to provide a list of Dog Id's to the Pets controller...
{ DogIds: [2,3,5] }
...where I link to existing Dogs in my database by the list of DogIds, and then have Entity Framework "automatically" link those actual entities in the Dogs List so that myPets.Dogs.First()
will actually give me the dog with the provided id 2.
I've successfully done this with single entities by having a public int DogId
with a public Dog Dog
by defining
modelBuilder.Entity<Pets>()
.HasOne(p => p.Dog)
.WithMany()
.HasForeignKey(p => p.DogId);
and then telling my controller
Pets pets = _context.Pets.Include(b => b.Dog).FirstOrDefault();
this will give me an actual Entity when I call pets.Dog
But in the case of many DogIds
each to their own single Dog
I'm really not sure how to describe this relationship, so that _context.Pets.Include(b => b.Dog).FirstOrDefault().Dogs
gives me something other than []
.
Is this still technically a one to one relationship, and how do I define the type of relationship this is to actually make this work?
I've seen a lot of examples of how to do this at the query level, but I'd really like to leverage the framework here to do the heavy lifting if it's possible.