[英]Entity Framework Core null object one-to-one
Entity Framework Core null object. 实体框架核心的空对象。 I have a one-to-one entity relationship.
我有一对一的实体关系。
public class Player
{
public int Id { get; set; }
public int? RatingId { get; set; }
public Rating Rating { get; set; }
}
public class Rating
{
public double Mean { get; set; }
}
In my player controller I return 在播放器控制器中,我返回
var player = await _context.Player.FindAsync(id);
However this is my json 但是这是我的json
{
"id": 3010,
"ratingId": 2009,
"rating": null,
"displayName": "Conor",
"partialPlayPercentage": 0.5,
"partialUpdatePercentage": 1
}
Is rating supposed to be null here? 评级在这里应该为空吗?
FTI When I call FTI当我打电话时
var rating = await _context.Rating.FindAsync(2009);
I get the correct rating 我得到正确的评分
Is rating supposed to be null here?
评级在这里应该为空吗?
Yes, except you have Lazy loading enabled, which in EF Core is not by default. 是的,除了您启用了延迟加载外,默认情况下,EF Core中未启用延迟加载 。
I would suggest you reading the whole Loading Related Data EF Core documentation topic which explains the 3 supported patterns - Eager, Explicit and Lazy loading. 我建议您阅读整个“ 加载相关数据 EF核心”文档主题,该主题说明了3种受支持的模式-早期,显式和延迟加载。 Note that there is no implicit loading, so you have to use one of those in order to get your navigation property loaded.
请注意,没有隐式加载,因此您必须使用其中之一才能加载导航属性。
For instance, the explicit loading: 例如,显式加载:
var player = await _context.Player.FindAsync(id);
if (player != null)
_context.Entry(player).Reference(e => e.Rating).Load();
The eager loading with Include
/ ThenInclude
is more natural choice, but it can't be used with Find
/ FindAsync
, so you need to use FirstOrDefault
/ SingleOrDefault
(or their Async
counterparts) like this: 急切地使用
Include
/ ThenInclude
加载是更自然的选择,但不能与Find
/ FindAsync
一起使用,因此您需要像这样使用FirstOrDefault
/ SingleOrDefault
(或它们的Async
对应对象):
var player = await _context.Player
.Include(e => e.Rating)
.FirstOrDefaultAsync(e => e.Id == id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.