简体   繁体   中英

Entity framework 3 table join with one right join

I have 3 tables:

strings
-----------
- string_id
- fallback_text

translations
----------------------
- translation_id
- string_id
- locale_id
- text

locales
---------------------
- locale_id

I want to achieve a resultset like this:

string_id | locale_id | text
----------------------------
1         | en_US     | bread
1         | es_ES     | pan
1         | fr_FR     | NULL

There is no translation for "bread" in french, but I want it in the results.

In SQL would be somethink like:

SELECT strings.string_id, locales.locale_id, translations.text
FROM strings
JOIN translations on strings.string_id = translations.string_id
RIGHT JOIN locales on translations.locale_id = locales.locale_id

This SELECT doesn't resolve my problem. What I want is to list every string who hasn't a translation in each locale existing in locales table. I think this isn't going to happen in a SELECT statement.

Imagine we have: locales table:

|locale_id|
-----------
|en_US    |
|es_ES    |

strings table:

|string_id|fallback_text|
-------------------------
|1        |bread        |
|2        |water        |

translations table:

|translation_id|string_id|locale_id|translation
-----------------------------------------------
|1             |1        |en_US    |bread
|2             |2        |es_ES    |agua

I would like to achieve this resultset:

string_id | locale_id | text
----------------------------
1         | en_US     | bread
1         | es_ES     | NULL
2         | en_US     | NULL
2         | es_ES     | agua

Thanks in advance.

The easiest way to accomplish this is simply use a SQL view.

Create an SQL view with you select statement, then create an entity to match that view. This entity will have 3 properties string_id, locale_id, text. Make sure that this entity defines (string_id and locale_id) as primary key. If you are using code first your mappings would be something like:

ToTable("MyViewName");
HasKey(x => new { x.string_id, x.locale_id });
var query = from s in db.strings
            from t in db.translation
            where s.string_id == t.string_id
            select new {s.stringid, t.locale_id, t.text }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM