实体框架Linq查询返回MySQL数据库的错误值

时间:2012-10-05 16:46:43

标签: mysql linq entity-framework

我有一个查询:

    var cams = (from c in db.cameras
                        join s in db.camera_sites on c.camera_site_id equals s.id
                        join o in db.servers on s.server_id equals o.id
                        where (c.enabled == "yes"
                        && s.enabled == "yes"
                        && o.enabled == "yes" 
                        && o.type == "hosted"
                        && o.server_method == "webservices"
                        && c.account_id == accountId)
                        select new EventCamera_Named { Camera = c, SiteName = s.name, ServerName = o.name }).ToList();

问题是所选的SiteName与Camera.name

相同

生成的sql是:

    SELECT
    `Filter1`.`id`, 
    `Filter1`.`account_id`, 
    `Filter1`.`camera_site_id`, 
    `Filter1`.`enabled`, 
    `Filter1`.`name`, 
    ...,
    `Filter1`.`name` AS `name1`, 
    `Extent3`.`name` AS `name2`

    FROM (SELECT
    `Extent1`.`id`, 
    `Extent1`.`account_id`, 
    `Extent1`.`camera_site_id`, 
    `Extent1`.`enabled`, 
    `Extent1`.`name`, 
    ..., 
    `Extent2`.`id` AS `id1`, 
    `Extent2`.`account_id` AS `account_id1`, 
    `Extent2`.`server_id`, 
    ...
    FROM `cameras` AS `Extent1` INNER JOIN `camera_sites` AS `Extent2` ON `Extent1`.`camera_site_id` = `Extent2`.`id`
    WHERE ('yes' = `Extent1`.`enabled`) AND ('yes' = `Extent2`.`enabled`)) AS `Filter1` INNER JOIN `servers` AS `Extent3` ON `Filter1`.`server_id` = `Extent3`.`id`
    WHERE ((('yes' = `Extent3`.`enabled`) AND ('hosted' = `Extent3`.`type`)) AND ('webservices' = `Extent3`.`server_method`)) AND (`Filter1`.`account_id` = 39884476)

如何重写我的查询返回正确的值以及导致它混淆的原因?

1 个答案:

答案 0 :(得分:0)

当我在db之后直接移动enabled检查时,它引用了它生成的sql是正确的。

    var cams = (from c in db.cameras 
                    where c.enabled == "yes"
                    join s in db.camera_sites on c.camera_site_id equals s.id 
                    where s.enabled == "yes"
                    join o in db.servers on s.server_id equals o.id
                    where (o.enabled == "yes" 
                    && o.type == "hosted"
                    && o.server_method == "webservices"
                    && c.account_id == accountId)
                    select new EventCamera_Named { Camera = c, SiteName = s.name, ServerName = o.name }).ToList();