简体   繁体   中英

how to use EF to select using DISTINCT and FOREIGN KEY together

This may be very basic, but here we go, as I can´t solve that for now.

I´m using Entity Frameword for Oracle (Managed Driver) and would like to do get all following:

I have 2 database tables as follows:

    TABLE_USER

    ID   INTEGER
    NAME STRING
    AGE  INTEGER

Content:

    0 JOHN 39
    1 MARY 40
    2 ALBERT 41
    3 ROBERT 42
    4 SARAH 43
    5 PETER 44



    TABLE_EVENTS

    ID         INTEGER
    EVENT_NAME STRING
    USER_ID    INTEGER (FOREIGN KEY TO TABLE_USER.ID)

Content:

    0 CREATE 1
    1 CREATE 2 
    2 CREATE 5
    3 DELETE 3
    4 DELETE 0
    5 CREATE 1
    6 DELETE 3
    7 CREATE 0
    8 UPDATE 4
    9 UPDATE 5
    10 DELETE 1

I need to get all DISTINCT values from TABLE_EVENTS where the user age in TABLE_USER is of a certain condition (like AGE <= 40 ).

That example would give me the following list: CREATE DELETE

My code shall look like:

    IQueryable<TABLE_USER> tableUser = dbContext.TABLE_USER;
    IQueryable<TABLE_EVENTS> tableEvents = dbContext.TABLE_EVENTS;

    ///
    /// Build the query
    /// 
    tableUserQuery = tableUser.Where(record => record => USER_ID == ??tableUser.ID?? &&
                                     ??tableUser.AGE < 30?? ).GroupJoin(???);
    ///
    /// Execute que query
    /// 
    var dbList = query.ToList();

I was looking at GroupJoin and other stuff, but I can´t even figure out how to built this query, so all I´ve posted is a skeleton...

Appreciate any kind of help.

typically if 2 tables are linked by foreign key, EF generates the navigation property to reach the other entity and you can use this query.

List<string> events = dbContext.TABLE_EVENTS.Where(te=>te.TABLE_USER.AGE < 30).Select(te=>te.EVENT_NAME).Distinct().ToList();

If you don't see the foreign entity linked, then the query is

List<string> events = dbContext.TABLE_EVENTS.Join(dbContext.TABLE_USERS, te=>te.USER_ID, tu=>tu.ID, (te,tu)=> te).Where(te=>te.TABLE_USER.AGE < 30).Select(te=>te.EVENT_NAME).Distinct().ToList();

the above query basically does an inner join on the user id, applies the filter and gets the distinct values.

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