0

I've got table

Tourists

  1. Tourist_ID

    2.Name


Extra_Charges

  1. Extra_Charge_ID
  2. Description

Toutist_Extra_Charges

  1. Tourist_Extra_Charge_ID - primary key
  2. Tourist_ID - foreign key
  3. Extra_Charge_ID - foreign key

I try to make this sql query using entity framework ent

    "Select Tourist.Name, Extra_Charges.Extra_Charge_Description, FROM Tourist

LEFT JOIN TOURIST_EXTRA_CHARGES on Tourist.Tourist_ID = TOURIST_EXTRA_CHARGES.Tourist_ID 
LEFT Join EXTRA_CHARGES on TOURIST_EXTRA_CHARGES.Extra_Charge_ID = EXTRA_CHARGES.Extra_Charge_ID
WHERE Tourist.Tourist_ID=86

I want to get the name of the tourist with id=86(event if he doesn't have extra_charges) AND IF HE DOES HAVE EXTRA_CHARGES - THE DESCRIPTION OF THE EXTRA_CHARGE

As I'm new to entity framework I tried the following

foreach (var tourist in db2.Tourist.Include("TOURIST_EXTRA_CHARGES").Include("EXTRA_CHARGES").Where(x=>x.Tourist_ID==86))
                  {
                      lblproba.Text+="Name" + tourist.Name_kir+" Description" + tourist.TOURIST_EXTRA_CHARGES.//don't have access to extra_charges table


                  }

But when I type tourist.TOURIST_EXTRA_CHARGES I don't have access to extra_charges table and its Description column


EDIT:

I read that to use the entity framework mapping with many-to-manyrelationship i should delete my column TOURIST_EXTRA_CHARGE_ID and make compository primary key. But when I did that - and made new edmx model - I now can't see my Tourist_Extra_Charges table. And nomatter how many times i created the model - this table didn't occur in the model

4

2 回答 2

1

I now can't see my Tourist_Extra_Charges table

That's expected for the link table in a many-to-many relationship and you don't need this table as an entity.

Your Tourist entity should now have a collection EXTRA_CHARGES and you can perform your query like so:

var tourist = db2.Tourist
    .Include("EXTRA_CHARGES")
    .SingleOrDefault(t => t.Tourist_ID == 86);

if (tourist != null)
{
    lblproba.Text += "Name "
        + tourist.Name_kir
        + " Description "
        + string.Join(", ", tourist.EXTRA_CHARGES.Select(e => e.Description));
}

I have replaced the foreach loop by SingleOrDefault because you are querying by the primary key which can only have one result (or none). The EXTRA_CHARGES.Select(e => e.Description) extracts the description from each extra charge and returns a new collection of strings. string.Join concats all those descriptions in the collection together and separates them by a comma.

于 2013-09-25T18:41:30.547 回答
0

Your database structure is wrong. If you need to link 2 tables using many2many relationship, you must add one more table, so called a "bridge" table containing 2 PKs from your other 2 tables. And when you have it, the EF will automatically resolve it as a relation property as "many2many"

于 2013-10-03T11:04:35.917 回答