Entity Framework query - return unique rows from child table

老子叫甜甜 提交于 2019-12-12 01:38:42

问题


I have Entity Framework model as below and data in the corresponding database tables:

Question: How do I query the model for returning all the rows (full entities, not anonymous type) from sales_type relevant to a given person ?

If the data is as above, then for John, the query should return first three rows from sales_type-table and for Mark it should return the rows 2 and 5.


回答1:


Something like this

ctx.PersonSales
   .Where(ps=> ps.Person.Id = myPersonId)
   .Where(ps=> ps.SalesMapping != null && ps.SalesMapping.SalesType != null)
   .Select(ps=>ps.SalesMapping.SalesType)
   .Distinct();



回答2:


Maybe something like this:

var personId=1;
var result= (
        from salesType in db.sales_type
        where
            (
                from salesMapping in db.sales_mapping
                join personSale in db.person_Sales
                    on salesMapping.id equals personSale.sales_mapping_id
                join person in db.person
                    on personSale.person_id equals person.id
                where
                    person.Id == personId
                select salesMapping.sales_type_id
            ).Contains(salesType.id)
        select salesType
    ).ToList();

Where db is the linq data context



来源:https://stackoverflow.com/questions/21877293/entity-framework-query-return-unique-rows-from-child-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!