简体   繁体   English

如何使用EF选择DISTINCT和FOREIGN KEY一起使用

[英]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: 我正在使用Oracle的实体框架字(托管驱动程序),并且希望获得以下所有信息:

I have 2 database tables as follows: 我有2个数据库表,如下所示:

    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 ). 我需要得到所有DISTINCT从值TABLE_EVENTS其中在用户年龄TABLE_USER是有一定的条件(如AGE <= 40 )。

That example would give me the following list: CREATE DELETE 该示例将为我提供以下列表: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... 我正在查看GroupJoin和其他内容,但是我什至无法弄清楚如何构建此查询,所以我发布的只是一个框架...

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. 通常,如果通过外键链接2个表,则EF会生成导航属性以到达另一个实体,您可以使用此查询。

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. 上面的查询基本上对用户ID进行了内部联接,应用了过滤器并获得了不同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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