Last active
July 25, 2019 04:54
-
-
Save anuraj/6cb319eb68ee56d9bd4f29b80f8d2f9f to your computer and use it in GitHub Desktop.
EF Core - FirstOrDefaultAsync throws Null Reference Exception - Code sample to reproduce the issue.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UsersController : Controller | |
{ | |
private readonly DatabaseContext _databaseContext; | |
public UsersController(DatabaseContext databaseContext) | |
{ | |
_databaseContext = databaseContext; | |
} | |
public async Task<ActionResult<User>> Get(int id) | |
{ | |
var user = await _databaseContext.Users.FirstOrDefaultAsync(x => x.Id == id); | |
if (user == null) | |
{ | |
return NotFound(); | |
} | |
return user; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UsersControllerTests | |
{ | |
[Fact] | |
public async Task VerifyGetMethodByIdReturnsNotFoundIfUserDoesntExists() | |
{ | |
using (var dbContext = await GetDatabaseContext()) | |
{ | |
var userController = new UsersController(dbContext); | |
var user = await userController.Get(100); | |
Assert.NotNull(user); | |
} | |
} | |
private async Task<DatabaseContext> GetDatabaseContext() | |
{ | |
var options = new DbContextOptionsBuilder<DatabaseContext>() | |
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) | |
.Options; | |
var databaseContext = new DatabaseContext(options); | |
databaseContext.Database.EnsureCreated(); | |
if (await databaseContext.Users.CountAsync() <= 0) | |
{ | |
for (int i = 1; i <= 10; i++) | |
{ | |
databaseContext.Users.Add(new User() | |
{ | |
Id = i, | |
Email = $"testuser{i}@example.com", | |
IsLocked = false, | |
CreatedBy = "SYSTEM", | |
CreatedDate = DateTime.UtcNow | |
}); | |
await databaseContext.SaveChangesAsync(); | |
} | |
} | |
return databaseContext; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment