Related Entity Query












0















I have a database with thee tables - Organisations, Locations and OrganisationLocations for example. Organisations holds information on companies, Locations holds information on offices address, and OrganisationLocations holds the many-to-many relationship info about the companies and their addresses. For example Company A might be locations X and Y, Company B might be in locations Y and Z.



These are the generated classes



public partial class Locations
{
public Locations()
{
OrganisationLocations = new HashSet<OrganisationLocations>();
}

public long Id { get; set; }
public string Description { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string PostCode { get; set; }
public string Name { get; set; }

public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }
}


public partial class Organisations
{
public Organisations()
{
OrganisationLocations = new HashSet<OrganisationLocations>();
}

public long Id { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public string ContactName { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }

public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }

}


public partial class OrganisationLocations
{
public long Id { get; set; }
public long OrganisationId { get; set; }
public long LocationId { get; set; }

public virtual Locations Location { get; set; }
public virtual Organisations Organisation { get; set; }
}


The DB Context looks like this:



public class PfApiContext : DbContext
{

public PfApiContext(DbContextOptions<PaymentAPIContext> options)
: base(options)
{
}

public DbSet<Locations> Locations { get; set; }
public DbSet<Organisations> Organisations { get; set; }
public virtual DbSet<OrganisationLocations> OrganisationLocations { get; set; }


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OrganisationLocations>(entity =>
{

entity.HasOne(d => d.Location)
.WithMany(p => p.OrganisationLocations)
.HasForeignKey(d => d.LocationId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_84m7dbl1gv1p6tg1wquwm8j5u");

entity.HasOne(d => d.Organisation)
.WithMany(p => p.OrganisationLocations)
.HasForeignKey(d => d.OrganisationId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_r0mkkndb6c2tr9nl0rgjm068t");
});

}
}


How would I get, for example, all the company data for all the companies in Location X? At the point I'm querying this I actually know the LocationID, so the SQL would be



SELECT  * FROM [dbo].[Organisations] WHERE Id IN (SELECT [OrganisationId] FROM [dbo].[OrganisationLocations] WHERE [LocationId] = 1)


This is probably really simple and I'm just being stupid, but I'm new to EFCore and LINQ, and the syntax of this has me scratching my head.
Selecting locations based on a location name I can understand



var locationUsers = await _pfApiContext.UserLocations.Where
(o => o.LocationName == locationName).ToListAsync();



but this is confusing me something terrible.



Thanks for any help










share|improve this question









New contributor




Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    0















    I have a database with thee tables - Organisations, Locations and OrganisationLocations for example. Organisations holds information on companies, Locations holds information on offices address, and OrganisationLocations holds the many-to-many relationship info about the companies and their addresses. For example Company A might be locations X and Y, Company B might be in locations Y and Z.



    These are the generated classes



    public partial class Locations
    {
    public Locations()
    {
    OrganisationLocations = new HashSet<OrganisationLocations>();
    }

    public long Id { get; set; }
    public string Description { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
    public string PostCode { get; set; }
    public string Name { get; set; }

    public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }
    }


    public partial class Organisations
    {
    public Organisations()
    {
    OrganisationLocations = new HashSet<OrganisationLocations>();
    }

    public long Id { get; set; }
    public string Name { get; set; }
    public string Owner { get; set; }
    public string ContactName { get; set; }
    public string Email { get; set; }
    public string Telephone { get; set; }

    public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }

    }


    public partial class OrganisationLocations
    {
    public long Id { get; set; }
    public long OrganisationId { get; set; }
    public long LocationId { get; set; }

    public virtual Locations Location { get; set; }
    public virtual Organisations Organisation { get; set; }
    }


    The DB Context looks like this:



    public class PfApiContext : DbContext
    {

    public PfApiContext(DbContextOptions<PaymentAPIContext> options)
    : base(options)
    {
    }

    public DbSet<Locations> Locations { get; set; }
    public DbSet<Organisations> Organisations { get; set; }
    public virtual DbSet<OrganisationLocations> OrganisationLocations { get; set; }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    modelBuilder.Entity<OrganisationLocations>(entity =>
    {

    entity.HasOne(d => d.Location)
    .WithMany(p => p.OrganisationLocations)
    .HasForeignKey(d => d.LocationId)
    .OnDelete(DeleteBehavior.ClientSetNull)
    .HasConstraintName("FK_84m7dbl1gv1p6tg1wquwm8j5u");

    entity.HasOne(d => d.Organisation)
    .WithMany(p => p.OrganisationLocations)
    .HasForeignKey(d => d.OrganisationId)
    .OnDelete(DeleteBehavior.ClientSetNull)
    .HasConstraintName("FK_r0mkkndb6c2tr9nl0rgjm068t");
    });

    }
    }


    How would I get, for example, all the company data for all the companies in Location X? At the point I'm querying this I actually know the LocationID, so the SQL would be



    SELECT  * FROM [dbo].[Organisations] WHERE Id IN (SELECT [OrganisationId] FROM [dbo].[OrganisationLocations] WHERE [LocationId] = 1)


    This is probably really simple and I'm just being stupid, but I'm new to EFCore and LINQ, and the syntax of this has me scratching my head.
    Selecting locations based on a location name I can understand



    var locationUsers = await _pfApiContext.UserLocations.Where
    (o => o.LocationName == locationName).ToListAsync();



    but this is confusing me something terrible.



    Thanks for any help










    share|improve this question









    New contributor




    Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      0












      0








      0








      I have a database with thee tables - Organisations, Locations and OrganisationLocations for example. Organisations holds information on companies, Locations holds information on offices address, and OrganisationLocations holds the many-to-many relationship info about the companies and their addresses. For example Company A might be locations X and Y, Company B might be in locations Y and Z.



      These are the generated classes



      public partial class Locations
      {
      public Locations()
      {
      OrganisationLocations = new HashSet<OrganisationLocations>();
      }

      public long Id { get; set; }
      public string Description { get; set; }
      public string City { get; set; }
      public string Street { get; set; }
      public string PostCode { get; set; }
      public string Name { get; set; }

      public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }
      }


      public partial class Organisations
      {
      public Organisations()
      {
      OrganisationLocations = new HashSet<OrganisationLocations>();
      }

      public long Id { get; set; }
      public string Name { get; set; }
      public string Owner { get; set; }
      public string ContactName { get; set; }
      public string Email { get; set; }
      public string Telephone { get; set; }

      public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }

      }


      public partial class OrganisationLocations
      {
      public long Id { get; set; }
      public long OrganisationId { get; set; }
      public long LocationId { get; set; }

      public virtual Locations Location { get; set; }
      public virtual Organisations Organisation { get; set; }
      }


      The DB Context looks like this:



      public class PfApiContext : DbContext
      {

      public PfApiContext(DbContextOptions<PaymentAPIContext> options)
      : base(options)
      {
      }

      public DbSet<Locations> Locations { get; set; }
      public DbSet<Organisations> Organisations { get; set; }
      public virtual DbSet<OrganisationLocations> OrganisationLocations { get; set; }


      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
      modelBuilder.Entity<OrganisationLocations>(entity =>
      {

      entity.HasOne(d => d.Location)
      .WithMany(p => p.OrganisationLocations)
      .HasForeignKey(d => d.LocationId)
      .OnDelete(DeleteBehavior.ClientSetNull)
      .HasConstraintName("FK_84m7dbl1gv1p6tg1wquwm8j5u");

      entity.HasOne(d => d.Organisation)
      .WithMany(p => p.OrganisationLocations)
      .HasForeignKey(d => d.OrganisationId)
      .OnDelete(DeleteBehavior.ClientSetNull)
      .HasConstraintName("FK_r0mkkndb6c2tr9nl0rgjm068t");
      });

      }
      }


      How would I get, for example, all the company data for all the companies in Location X? At the point I'm querying this I actually know the LocationID, so the SQL would be



      SELECT  * FROM [dbo].[Organisations] WHERE Id IN (SELECT [OrganisationId] FROM [dbo].[OrganisationLocations] WHERE [LocationId] = 1)


      This is probably really simple and I'm just being stupid, but I'm new to EFCore and LINQ, and the syntax of this has me scratching my head.
      Selecting locations based on a location name I can understand



      var locationUsers = await _pfApiContext.UserLocations.Where
      (o => o.LocationName == locationName).ToListAsync();



      but this is confusing me something terrible.



      Thanks for any help










      share|improve this question









      New contributor




      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      I have a database with thee tables - Organisations, Locations and OrganisationLocations for example. Organisations holds information on companies, Locations holds information on offices address, and OrganisationLocations holds the many-to-many relationship info about the companies and their addresses. For example Company A might be locations X and Y, Company B might be in locations Y and Z.



      These are the generated classes



      public partial class Locations
      {
      public Locations()
      {
      OrganisationLocations = new HashSet<OrganisationLocations>();
      }

      public long Id { get; set; }
      public string Description { get; set; }
      public string City { get; set; }
      public string Street { get; set; }
      public string PostCode { get; set; }
      public string Name { get; set; }

      public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }
      }


      public partial class Organisations
      {
      public Organisations()
      {
      OrganisationLocations = new HashSet<OrganisationLocations>();
      }

      public long Id { get; set; }
      public string Name { get; set; }
      public string Owner { get; set; }
      public string ContactName { get; set; }
      public string Email { get; set; }
      public string Telephone { get; set; }

      public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }

      }


      public partial class OrganisationLocations
      {
      public long Id { get; set; }
      public long OrganisationId { get; set; }
      public long LocationId { get; set; }

      public virtual Locations Location { get; set; }
      public virtual Organisations Organisation { get; set; }
      }


      The DB Context looks like this:



      public class PfApiContext : DbContext
      {

      public PfApiContext(DbContextOptions<PaymentAPIContext> options)
      : base(options)
      {
      }

      public DbSet<Locations> Locations { get; set; }
      public DbSet<Organisations> Organisations { get; set; }
      public virtual DbSet<OrganisationLocations> OrganisationLocations { get; set; }


      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
      modelBuilder.Entity<OrganisationLocations>(entity =>
      {

      entity.HasOne(d => d.Location)
      .WithMany(p => p.OrganisationLocations)
      .HasForeignKey(d => d.LocationId)
      .OnDelete(DeleteBehavior.ClientSetNull)
      .HasConstraintName("FK_84m7dbl1gv1p6tg1wquwm8j5u");

      entity.HasOne(d => d.Organisation)
      .WithMany(p => p.OrganisationLocations)
      .HasForeignKey(d => d.OrganisationId)
      .OnDelete(DeleteBehavior.ClientSetNull)
      .HasConstraintName("FK_r0mkkndb6c2tr9nl0rgjm068t");
      });

      }
      }


      How would I get, for example, all the company data for all the companies in Location X? At the point I'm querying this I actually know the LocationID, so the SQL would be



      SELECT  * FROM [dbo].[Organisations] WHERE Id IN (SELECT [OrganisationId] FROM [dbo].[OrganisationLocations] WHERE [LocationId] = 1)


      This is probably really simple and I'm just being stupid, but I'm new to EFCore and LINQ, and the syntax of this has me scratching my head.
      Selecting locations based on a location name I can understand



      var locationUsers = await _pfApiContext.UserLocations.Where
      (o => o.LocationName == locationName).ToListAsync();



      but this is confusing me something terrible.



      Thanks for any help







      code-first ef-core-2.0






      share|improve this question









      New contributor




      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited Jan 18 at 15:02







      Andrew Bailie













      New contributor




      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Jan 18 at 14:00









      Andrew BailieAndrew Bailie

      12




      12




      New contributor




      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Andrew Bailie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I would remove the virtual collections and objects from all three classes and then remove the Id field (assuming it's the primary key) in the OrganisationLocations table. The OrganisationId and the LocationId fields in the OrganisationLocations should be both the primary keys and the foreign keys in order to make it a many-to-many relationship between OrganisationLocations, Locations, and Organisation. Then you can use Linq to do a simple join query to get the info you're looking for. For example:



                      var orgs = (from ol in PfApiContext.OrganisationLocations
          inner join o in PfApiContext.Organisation on o.Id equals ol.OrganisationId
          inner join l in PfApiContext.Locations on ol.LocationId equals l.Id
          where ol.LocationId = 1
          select new Organisation()
          {
          Id = o.Id,
          Name = o.Name,
          Owner = o.Ower,
          etc...

          }





          share|improve this answer
























          • Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

            – Andrew Bailie
            yesterday











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Andrew Bailie is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54255543%2frelated-entity-query%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          I would remove the virtual collections and objects from all three classes and then remove the Id field (assuming it's the primary key) in the OrganisationLocations table. The OrganisationId and the LocationId fields in the OrganisationLocations should be both the primary keys and the foreign keys in order to make it a many-to-many relationship between OrganisationLocations, Locations, and Organisation. Then you can use Linq to do a simple join query to get the info you're looking for. For example:



                      var orgs = (from ol in PfApiContext.OrganisationLocations
          inner join o in PfApiContext.Organisation on o.Id equals ol.OrganisationId
          inner join l in PfApiContext.Locations on ol.LocationId equals l.Id
          where ol.LocationId = 1
          select new Organisation()
          {
          Id = o.Id,
          Name = o.Name,
          Owner = o.Ower,
          etc...

          }





          share|improve this answer
























          • Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

            – Andrew Bailie
            yesterday
















          0














          I would remove the virtual collections and objects from all three classes and then remove the Id field (assuming it's the primary key) in the OrganisationLocations table. The OrganisationId and the LocationId fields in the OrganisationLocations should be both the primary keys and the foreign keys in order to make it a many-to-many relationship between OrganisationLocations, Locations, and Organisation. Then you can use Linq to do a simple join query to get the info you're looking for. For example:



                      var orgs = (from ol in PfApiContext.OrganisationLocations
          inner join o in PfApiContext.Organisation on o.Id equals ol.OrganisationId
          inner join l in PfApiContext.Locations on ol.LocationId equals l.Id
          where ol.LocationId = 1
          select new Organisation()
          {
          Id = o.Id,
          Name = o.Name,
          Owner = o.Ower,
          etc...

          }





          share|improve this answer
























          • Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

            – Andrew Bailie
            yesterday














          0












          0








          0







          I would remove the virtual collections and objects from all three classes and then remove the Id field (assuming it's the primary key) in the OrganisationLocations table. The OrganisationId and the LocationId fields in the OrganisationLocations should be both the primary keys and the foreign keys in order to make it a many-to-many relationship between OrganisationLocations, Locations, and Organisation. Then you can use Linq to do a simple join query to get the info you're looking for. For example:



                      var orgs = (from ol in PfApiContext.OrganisationLocations
          inner join o in PfApiContext.Organisation on o.Id equals ol.OrganisationId
          inner join l in PfApiContext.Locations on ol.LocationId equals l.Id
          where ol.LocationId = 1
          select new Organisation()
          {
          Id = o.Id,
          Name = o.Name,
          Owner = o.Ower,
          etc...

          }





          share|improve this answer













          I would remove the virtual collections and objects from all three classes and then remove the Id field (assuming it's the primary key) in the OrganisationLocations table. The OrganisationId and the LocationId fields in the OrganisationLocations should be both the primary keys and the foreign keys in order to make it a many-to-many relationship between OrganisationLocations, Locations, and Organisation. Then you can use Linq to do a simple join query to get the info you're looking for. For example:



                      var orgs = (from ol in PfApiContext.OrganisationLocations
          inner join o in PfApiContext.Organisation on o.Id equals ol.OrganisationId
          inner join l in PfApiContext.Locations on ol.LocationId equals l.Id
          where ol.LocationId = 1
          select new Organisation()
          {
          Id = o.Id,
          Name = o.Name,
          Owner = o.Ower,
          etc...

          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 18 at 17:45









          user10728126user10728126

          1




          1













          • Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

            – Andrew Bailie
            yesterday



















          • Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

            – Andrew Bailie
            yesterday

















          Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

          – Andrew Bailie
          yesterday





          Thanks for your response. The database was set up the way you recommended until I tried to generate the entities, at which point VS told me I needed a primary key column in the OrganisationLocations table. It also created all the virtual collections, which I assumed would need to be used for this very scenario.

          – Andrew Bailie
          yesterday










          Andrew Bailie is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Andrew Bailie is a new contributor. Be nice, and check out our Code of Conduct.













          Andrew Bailie is a new contributor. Be nice, and check out our Code of Conduct.












          Andrew Bailie is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54255543%2frelated-entity-query%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Callistus III

          Plistias Cous

          Index Sanctorum