使用可以为null的字段在数据库中搜索对象

时间:2016-07-13 20:14:34

标签: c# linq-to-sql

我试图通过针对它们的本地副本检查这些字段来检索表中的对象

Bin(非空),IPN(非空),位置ID(非空),计数日期(非空),批次标记(可空)和序列号(可空)。

如果我不包含批次或序列,它可以正常工作 - 并且它将返回有很多标签的对象(在表中你可以有许多相同的项目,带有不同的批号或序列号)但它会永远不会返回批次标记/序列为空的那些

所以我的问题是如何搜索这些项目呢?这是代码行。如果我在末尾包含批次标记/序列内容,它将为null。但是如果我删除它,它将返回一个项目(除了我还需要它返回那些字段中包含null的项目。)

InventoryPhysicalCount editItem = DatabaseDataContext.InventoryPhysicalCounts.First(i => 
    i.Bin == LocalSelectedItem.Bin && i.IPN == LocalSelectedItem.IPN &&
    i.LocationId == LocalSelectedItem.LocationId &&
    i.CountDate == LocalSelectedItem.CountDate && 
    i.LotTag == LocalSelectedItem.LotTag && 
    i.SerialNumber == LocalSelectedItem.SerialNumber);

谢谢。

1 个答案:

答案 0 :(得分:1)

如果您希望所有记录都与Not Null字段匹配,并且Null字段为Null或与给定值匹配:

InventoryPhysicalCount editItem =   
    DatabaseDataContext.InventoryPhysicalCounts.First(i => 
        i.Bin == LocalSelectedItem.Bin && i.IPN == LocalSelectedItem.IPN &&
        i.LocationId == LocalSelectedItem.LocationId &&
        i.CountDate == LocalSelectedItem.CountDate && 
        (i.LotTag == null || i.LotTag == LocalSelectedItem.LotTag) && 
        (i.SerialNumber == null || i.SerialNumber == LocalSelectedItem.SerialNumber));

如果您想要与值匹配的记录(如果没有给出值则为Null,或者如果给出LocalSelectedItem值则为值):

InventoryPhysicalCount editItem =   
    DatabaseDataContext.InventoryPhysicalCounts.First(i => 
        i.Bin == LocalSelectedItem.Bin && i.IPN == LocalSelectedItem.IPN &&
        i.LocationId == LocalSelectedItem.LocationId &&
        i.CountDate == LocalSelectedItem.CountDate && 
        ((i.LotTag == null && LocalSelectedItem.LotTag == null) || i.LotTag == LocalSelectedItem.LotTag) && 
        ((i.SerialNumber == null && LocalSelectedItem.SerialNumber == null) || i.SerialNumber == LocalSelectedItem.SerialNumber));

如果您想忽略LocalSelectedItem值,如果它们为空:

InventoryPhysicalCount editItem =   
    DatabaseDataContext.InventoryPhysicalCounts.First(i => 
        i.Bin == LocalSelectedItem.Bin && i.IPN == LocalSelectedItem.IPN &&
        i.LocationId == LocalSelectedItem.LocationId &&
        i.CountDate == LocalSelectedItem.CountDate && 
        (LocalSelectedItem.LogTag == null || i.LotTag == LocalSelectedItem.LotTag) && 
        (LocalSelectedItem.SerialNumber == null || i.SerialNumber == LocalSelectedItem.SerialNumber));