我已经使用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
的错误。
P.S。:所有Id
s(其中3个)是typeof(int)
修改
这是生成的sql Query:
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<Part>();
}
public int Id { get; set; }
public Nullable<int> TipId { get; set; }
public Nullable<int> GivenId { get; set; }
public string FileId { get; set; }
public Nullable<bool> Carve { get; set; }
public Nullable<bool> Mina { get; set; }
public Nullable<bool> Deleted { get; set; }
public virtual Tip Tip { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Part> Parts { get; set; }
}
public partial class Tip
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Tip()
{
this.Items = new HashSet<Item>();
}
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> ModelId { get; set; }
public Nullable<bool> Deleted { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Item> Items { get; set; }
public virtual Model Model { get; set; }
}