c# - 访问具有 InverseProperty 注释的模型属性会导致 NullReferenceException
问题描述
注意:我确实从 .Find(id)“查询”中得到了有效的结果。当我访问“帖子”字段时,会引发 NullReferenceException。
我有 2 个模型类“Post”和“Thread”:
public class Post
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Text { get; set; }
public User User { get; set; }
public Thread Thread { get; set; }
}
public class Thread
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Title { get; set; }
public Section Section { get; set; }
[InverseProperty("Thread")]
public List<Post> Posts { get; set; }
}
据我了解,我应该能够通过访问属性“帖子”来获取链接到线程的所有帖子条目。
使用以下代码,我尝试访问该属性:
using (var dbcontext = new DataBaseContext()) // I get a connection to the database
{
Thread thread = dbcontext.Thread.Find(id); // I get a row from the table
foreach(var post in thread.Posts) // It's *here* that the exception is thrown
{
// do something with that data
}
}
结果是我得到了 NullReferenceException。我认为访问 Posts 属性(最初为 null,因为它不在数据库中)会导致延迟加载(因为它具有 InverseProperty 注释)。
解决方案
推荐阅读
- c# - 将数据库值绑定到 MaxLenght 属性
- html - 如何在相反方向添加背景颜色
- node.js - 是否可以在使用 pg-promise 的 INSERT 命令后获取“INSERT oid count”数据?
- prometheus - Prometheus alertmanager 倍增通知最重要
- php - 如何在codeigniter中获取多个通配符中的值
- vba - 命名范围更改时数据透视表不刷新[VBA]
- java - 如何在 SSL 配置的 tomcat 中缓存和更新 CRL(证书吊销列表)/OCSP 响应?
- python - GridSearchCV 在管道中将 fit_params 传递给 XGBRegressor 会产生“ValueError:需要超过 1 个值才能解包”
- java - 如何在 JavaFX 中将父级的大小与其子级的大小绑定,反之亦然?
- typescript - 缺少 CORS 标头“Access-Control-Allow-Origin”。发布到 API 时