Search code examples
c#entity-framework-corerelationshipone-to-many

How do I specify which column is the Foreign key and which column is the Primary Key on a one-to-many relationship. Using Entity Framework Core


I Have two tables like so

   public class Shepherd 
    {
 public long Id { get; set; }
 public string Name { get; set; }
 public string UserId{ get; set; }
}

   public class Goat 
    {
 public long Id { get; set; }
 public string Hairyness { get; set; }
 public string CreatedBy { get; set; }
}

I know how to create the one-to-many relationship using the Ids but I need to create a one-to-many relationship from Shepherd to many Goats using the UserId and 'CreatedBy' columns. I hope this makes sense. Thanks a lot in advance.


Solution

  • I found my own solution! Using Linq.

        var goatPoo = from Goats in _context.Goats
                  join Shepherd in _context.Shepherds
                  on Goats.CreatedBy equals Shepherd.UserId
                  where Shepherd.UserId == 77
                  select new { 
                      Shepherd.Id, 
                      Shepherd.Firstname, 
                      Shepherd.Lastname, 
                      Goats.Hairyness
                  };