实体框架存在子句与lambda

时间:2013-10-28 17:03:40

标签: entity-framework lambda

我已经看到了类似问题的答案(Entity framework and Exists clause),但没有使用lambda,我想了解错误, 是否是我的映射或是否是使用方式。我正在使用Entity Framework 5。

这是我的映射:

public class Attribute : EntityWithGuid
{
    ... Other mappings ....

    [InverseProperty("Attribute")]
    public virtual ICollection<CategoryAttribute> CategoryAttributes { get; set; }
}

public class Category : EntityWithGuid
{
    ... Other mappings ....

    [InverseProperty("Category")]
    public virtual ICollection<CategoryAttribute> CategoryAttributes { get; set; }
}

public class CategoryAttribute : EntityWithGuid
{
    ... Other mappings ....

    [ForeignKey("Category_Id")]
    public virtual Category Category { get; set; }
    public string Category_Id { get; set; }

    [ForeignKey("Attribute_Id")]
    public virtual Attribute Attribute { get; set; }
    public string Attribute_Id { get; set; }
}

如果我运行下面的命令,它运行正常,结果SQL是

var query = Attribute.Where(x => !x.CategoryAttributes.Any());

SELECT 
    Extent1.Id,
    Extent1.Name,
    Extent1.Type,
    Extent1.Active
FROM
    Attribute AS Extent1
WHERE
    NOT EXISTS( SELECT 
            1 AS C1
        FROM
            CategoryAttribute AS Extent2
        WHERE
            Extent1.Id = Extent2.Attribute_Id)

但是,如果我再添加一个子句,则出现属性的Project2别名而不是Extent1,并且因为在剩余的Extent1.Id

内的exists子句中出现错误
var query = Attribute.Where(x => !x.CategoryAttributes.Any(y=>y.Category_Id == idcategory));

SELECT 
    Project2.Id,
    Project2.Name,
    Project2.Type,
    Project2.Active
FROM
    Attribute AS Project2
WHERE
    NOT EXISTS( SELECT 
            1 AS C1
        FROM
            CategoryAttribute AS Extent2
        WHERE
            (Extent1.Id = Extent2.Attribute_Id)
                AND (Extent2.Category_Id = @p__linq__0))

例外是

  

'where子句'中的未知列'Extent1.Id'

1 个答案:

答案 0 :(得分:0)

发现问题。

执行一个简单的查询并收到类似的错误后,认为出了问题。在查询下面,SQL和不合需要的别名Project

User.Where(x => x.Name.Contains(partialName))

SELECT 
    Project1.Id,
    Project1.Name
FROM
    User AS Project1
WHERE
    (LOCATE('Marcelo', Extent1.Name)) > 0
ORDER BY Project1.Name ASC

最近我升级了MySql,随之而来的是新的Net连接器,版本6.7.4。我回到了之前的Net连接器版本(6.5.6),一切都恢复了。