【发布时间】:2020-09-17 04:42:07
【问题描述】:
我的问题是 - 如果数据库中的导航属性为“null”,我的查询将不会返回我正在查询的主要对象。
为了清楚起见,我的问题不是 .Include() 中的导航属性返回 null。我的问题是该属性预计为空,当它是时,市场不会被返回。
这是我的意思的一个例子:
我的代码:
markets = await _context.Markets
.Include(x => x.Agency)
.Include(x => x.Location)?.ThenInclude(x => x.State)?
.Include(x => x.Location).ThenInclude(x => x.Country)
.Where(x => x.Deleted == false
&& x.Agency.Deleted == false).ToListAsync();
我有一些市场,它们具有导航属性Location,而后者又具有导航属性State。对于某些Location,State 为空。在Location 模型中定义的State 的外键是long?。
但是,由于某种原因,结果列表中没有返回我的具有 null 状态的市场,而是返回了所有这些字段都包含在 .Include() 语句中且不为 null 的实体。
我最初的代码在包含之后没有?... 比如:
.Include(x => x.Location).ThenInclude(x => x.State) 并没有奏效。我添加了可以为空的想法,它可能会有所帮助,尽管它没有。
这里有人有什么建议吗?运行此语句时,我收到此异常:
.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
但是,该异常不会中断流程,并且返回的对象不具有 null State。
任何和所有提示将不胜感激!
编辑:
重要的是要注意,当我的所有导航属性都不为空时,代码可以正常工作。当 State 为 null(唯一可以为 null 的导航属性)时,就会出现此问题。
型号:
public class Market
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long MarketId { get; set; }
[ForeignKey("Location")]
public long HeadquartersId { get; set; }
[Required]
public virtual Location Location { get; set; }
}
public class Location
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long LocationId { get; set; }
[ForeignKey("State")]
public long? StateId { get; set; }
[ForeignKey("Country")]
public long CountryId { get; set; }
[Required]
public virtual State State { get; set; }
[Required]
public virtual Country Country { get; set; }
}
【问题讨论】:
-
你试过这个
.Include("Location").Include("Location.State")吗? -
@SowmyadharGourishetty 有趣的想法,我试了一下,不幸的是它没有用:(
-
你能展示模型及其配置吗?
-
@ESG 当然,我刚刚将我的模型包含在原始帖子的编辑中 - 希望它可以阐明这里出了什么问题。
-
必需的可能是一个问题,因为框架可能假定这些关系不是可选的。您是否尝试过在 DbContext 中将它们设为可选 va
OnModelCreating?
标签: c# linq entity-framework-core