gpt4 book ai didi

c# - NullReferenceException 在连接的字符串属性上使用 Where 查询 SQLite 数据库

转载 作者:太空狗 更新时间:2023-10-29 16:27:34 25 4
gpt4 key购买 nike

我正在尝试使用以下代码选择一条记录:

Location item = connection
.Table<Location>()
.Where(l => l.Label.Equals(label))
.FirstOrDefault();

这导致:

System.NullReferenceException: Object reference not set to an instance of an object.

当我在不同的属性(邮政编码)上尝试相同的操作时,即使没有找到任何记录,它也能正常工作。:

Location item = connection
.Table<Location>()
.Where(l => l.Postcode.Equals(label))
.FirstOrDefault();

这是位置类:

// These are the Locations where the Stock Take Sessions are done
public class Location : DomainModels, IComparable<Location>
{
[JsonProperty("id"), PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public int Number { get; set; }
public string Postcode { get; set; }
public string City { get; set; }
public bool Completed { get; set; }

[Ignore] // Removing this does not have an impact on the NullReferenceException
public string Label => $"{Name ?? ""} - ({Postcode ?? ""})";

public int CompareTo(Location other)
{
return Name.CompareTo(other.Name);
}

// Navigation property
// One to many relationship with StockItems
[OneToMany(CascadeOperations = CascadeOperation.All), Ignore]
public List<StockItem> StockItems { get; set; }

// Specify the foreign key to StockTakeSession
[ForeignKey(typeof(StockTakeSession))]
public int StockTakeSessionId { get; set; }

// One to one relationship with StockTakeSession
[OneToOne]
public StockTakeSession StockTakeSession { get; set; }

}

我做错了什么?

感谢您的任何建议!

最佳答案

你的 where 过滤器 在数据存储中 Label 但是你在类 Location 上的标记装饰了Label 属性与 IgnoreAttribute。这意味着 Label 属性将不会被设置,直到之后实体被具体化到内存并且您不能在数据存储中对其进行任何操作。

.Where(l => l.Label.Equals(label))

修复

有一些选项。

  • 您可以将其设置为计算列,并使用相同的逻辑在商店中创建一个计算列。这涉及直接在 RDBMS 管理器中手动更改表架构或编辑迁移脚本。该属性被标记为 [DatabaseGenerated(DatabaseGeneratedOption.Computed)](如果使用属性,您上面的代码就是)。
  • 您可以更改 Where 以过滤在商店中找到的组成 Label 的属性。即:.Where(l => l.Postcode.Equals(Postcode) && l.Name.Equals(Name))
  • 您可以将该特定过滤器之前的所有内容具体化到内存中,然后应用该过滤器。 如果到此为止的所有内容都会产生大量记录,则不推荐这样做。例如,使用下面的代码,如果表很大,您将检索单个记录的所有内容。

    Location item = connection
    .Table<Location>()
    .AsEnumerable()
    .Where(l => l.Label.Equals(label))
    .FirstOrDefault();

编辑

[Ignore] // Removing this does not have an impact on the NullReferenceException

不,它不应该,除非您将具有相同名称的列添加到现有模式用所有数据填充它。 (或在您的模式中创建同名的计算列)

关于c# - NullReferenceException 在连接的字符串属性上使用 Where 查询 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46362385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com