我已经看到了类似问题的答案(实体框架和 Exists 子句),但没有使用 lambda,我想了解什么是错误的,无论是我的映射还是使用方式。我正在使用实体框架 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 别名的 Attribute 而不是 Extent1 并给出错误,因为在剩余 Extent1.Id 内的存在子句内
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”