asp.net 在使用.NET EF Core DbContext属性之前,是否应使用null检查

vptzau2j  于 4个月前  发布在  .NET
关注(0)|答案(1)|浏览(73)

this tutorial之后,我得到的GetTodoItem(long id)方法与示例中的方法不同。它包括_context.TodoItems的null检查。现在,当编写我自己的控制器方法时,我想知道我是否应该执行这些null检查。
请注意,TodoContext属性是不可空的,但空示例化(= null!)。我目前在.NET 6上,但想知道答案是否与.NET 8不同。请记住,我是. NET新手。

public class TodoContext : DbContext {
    public TodoContext(DbContextOptions<TodoContext> options)
        : base(options)
    {}
    public DbSet<TodoItem> TodoItems { get; set; } = null!;
}

字符串

生成的代码

[HttpGet("{id}")]
public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
{
    var todoItem = await _context.TodoItems.FindAsync(id);
    if (todoItem == null) {
        return NotFound();
    }
    return todoItem;
}

我生成的代码

[HttpGet("{id}")]
public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
{
    if (_context.TodoItems == null) {
        return NotFound();
    }
    var todoItem = await _context.TodoItems.FindAsync(id);
    if (todoItem == null) {
        return NotFound();
    }
    return todoItem;
}


我遇到了两种不同的处理问题的方法。

kb5ga3dv

kb5ga3dv1#

在使用.NET EF Core DbContext属性之前,是否应使用null检查
不,DbSet属性是由EF Core管理的,如果它们由于某种原因将为null -有一些非常非常糟糕的事情发生,null检查将没有帮助。
至于props -您启用了nullable reference types功能,因此请查看使用可空引用类型:DbContext和DbSet,您可以将设置更改为:

public class TodoContext : DbContext {
    public TodoContext(DbContextOptions<TodoContext> options)
        : base(options)
    {}
    public DbSet<TodoItem> TodoItems => Set<TodoItem>();
}

字符串
所以= null!不会干扰眼睛。

相关问题