【问题标题】:Entity Framework Core null object one-to-oneEntity Framework Core 空对象一对一
【发布时间】:2018-09-14 15:45:50
【问题描述】:

Entity Framework Core 空对象。我有一对一的实体关系。

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; }
}

在我的播放器控制器中我返回

var player = await _context.Player.FindAsync(id);

不过这是我的 json

{
    "id": 3010,
    "ratingId": 2009,
    "rating": null,
    "displayName": "Conor",
    "partialPlayPercentage": 0.5,
    "partialUpdatePercentage": 1
}

这里的评分应该为空吗?

FTI 当我打电话时

var rating = await _context.Rating.FindAsync(2009);

我得到了正确的评价

【问题讨论】:

    标签: c# model null entity-framework-6 entity-framework-core


    【解决方案1】:

    这里的评分应该为空吗?

    是的,除非您启用了 Lazy loading,这在 EF Core 中是默认不启用的。

    我建议您阅读整个 Loading Related Data EF Core 文档主题,其中解释了 3 种支持的模式 - 急切、显式和延迟加载。请注意,没有 隐式 加载,因此您必须使用其中之一才能加载导航属性。

    例如,显式加载:

    var player = await _context.Player.FindAsync(id);
    if (player != null)
        _context.Entry(player).Reference(e => e.Rating).Load();
    

    使用Include / ThenInclude 进行预加载是更自然的选择,但它是can't be used with Find / FindAsync,因此您需要像这样使用FirstOrDefault / SingleOrDefault(或他们的Async 对应项):

    var player = await _context.Player
        .Include(e => e.Rating)
        .FirstOrDefaultAsync(e => e.Id == id);
    

    【讨论】:

      猜你喜欢
      • 2017-02-17
      • 2019-08-07
      • 1970-01-01
      • 2020-08-10
      • 2019-11-11
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多