How to navigate multiple relationships using LINQ to Entities?

I am just starting with LINQ to Entities, and I am trying to replicate the search we are doing in the stored procedure as a LINQ to Entities query. However, I cannot imagine the correct way to request the properties of objects of more than one “connection” from the starting point of my request.

For example, let's say I have Campaign, CampaignLocation, and Location tables that have foreign keys from Campaign to CampaignLocation and CampaignLocation to Location. A fairly standard many-to-many table configuration. When I start writing my LINQ query as follows:

 var campaigns = from c in context.Campaign.CampaignLocation

that as far as possible in the chain of associations. There is no “Location” property in “CampaignLocation” so I can filter the Location properties.

I tried using the LINQ join syntax as follows:

 var campaigns = from c in context.Campaign
                 join cl in context.CampaignLocation 
                   on c.CampaignID equals cl.CampaignID

But it seems that the property "CampaignID" in the alias "cl" does not exist. Which is really strange, there is a column named so on the table. Is it not on the model object, since it is a foreign key in the campaign table?

Where am I wrong here and what am I missing?

[UPDATE]

It seems that any integer columns that I use for foreign keys are not added as properties of model objects. Foreign key relationships are displayed, but no identifier properties. Is there a way to get the constructor to add these properties to the model when I read the schema from the database?

+3
3

- , , EF ComaignLocation ↔ Location? , , (join ..), linq join, linq- ( ) proc, . , EF.

:

, , . EFModel.

+1

?

    Campaign campaign1 = context.Campaigns.Where(x => x.CampaignID == 1).Single();
    foreach (CampaignLocation campaignlocation in campaign1.CampaignLocations)
    {
        Response.Write(campaignlocation.Location.Name + "<br />");
    }

    Location location1 = context.Locations.Where(x => x.LocationID == 3).Single();
    foreach (CampaignLocation campaignlocation in location1.CampaignLocations)
    {
        Response.Write(campaignlocation.Campaign.Name + "<br />");
    }

( , ...)

0

Alternative answer. Do you need to manually edit / recreate your .edmx file if you have modified the database since you created it?

0
source

Source: https://habr.com/ru/post/1703572/


All Articles