Linq Any总是返回true

我已经使用Linq to Entities多年了,但这是我第一次遇到这个问题。 我有提示项目表,每个提示可以有很多项目。我在数据库中只有3个项目。 在编辑项目时,我想确保GivenId字段对于具有相同提示的项目是唯一的。 我用这个:

Item item =db.Items.FirstOrDefault(c => c.Id == id); if (item != null) { if (db.Items .Any(x => x.GivenId == newGivenId && x.Id != item.Id && x.TipId == item.TipId)) { //newGivenId is either different or if it is the same, //it belongs to the same item } else { //newGivenId already exists for an Item in the same tip } } 

  db.Items .FirstOrDefault(x => x.GivenId == newGivenId && x.Id != item.Id && x.TipId == item.TipId); 

按预期返回null

我知道我可以像以下一样使用它:

 Item it = db.Items .FirstOrDefault(x => x.GivenId == newGivenId && x.Id != item.Id && x.TipId == item.TipId); if(it==null) { } else { } 

但我只想找到Any

PS:所有Id (其中3个)是typeof(int)

编辑:

这是生成的sql查询:

 DECLARE @p__linq__0 AS SQL_VARIANT; DECLARE @p__linq__1 AS SQL_VARIANT; DECLARE @p__linq__2 AS SQL_VARIANT; SET @p__linq__0 = NULL; SET @p__linq__1 = NULL; SET @p__linq__2 = NULL; SELECT CASE WHEN ( EXISTS (SELECT 1 AS [C1] FROM [dbo].[Items] AS [Extent1] WHERE ([Extent1].[GivenId] = @p__linq__0) AND ([Extent1].[Id]  @p__linq__1) AND (([Extent1].[TipId] = @p__linq__2) OR (([Extent1].[TipId] IS NULL) AND (@p__linq__2 IS NULL))) )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1] FROM ( SELECT 1 AS X ) AS [SingleRowTable1] 

EF生成的课程:

 public partial class Item { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Item() { this.Parts = new HashSet(); } public int Id { get; set; } public Nullable TipId { get; set; } public Nullable GivenId { get; set; } public string FileId { get; set; } public Nullable Carve { get; set; } public Nullable Mina { get; set; } public Nullable Deleted { get; set; } public virtual Tip Tip { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection Parts { get; set; } } public partial class Tip { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Tip() { this.Items = new HashSet(); } public int Id { get; set; } public string Name { get; set; } public Nullable ModelId { get; set; } public Nullable Deleted { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection Items { get; set; } public virtual Model Model { get; set; } }