I'm working on a project using .NET 8, Entity Framework Core and SQL Server. I have created a table called Accounts in my database using the following SQL script:
CREATE TABLE [dbo].[Accounts]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[AccountEmail] NVARCHAR (100) NOT NULL UNIQUE,
[HashedPassword] NVARCHAR (200) NOT NULL,
[DateOfBirth] DATETIMEOFFSET NOT NULL,
[RegisterDate] DATETIMEOFFSET NOT NULL,
CONSTRAINT [PK_Accounts] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
I have also created an entity class in C# to represent this table, as shown below:
public class Account : BaseModel
{
public required string AccountEmail { get; set; }
public required string HashedPassword { get; set; }
public DateTimeOffset DateOfBirth { get; set; }
public DateTimeOffset RegisterDate { get; set; }
public User? User { get; set; }
}
Despite these configurations, when I try to add a new account, I get the following error:
Invalid column name 'AccountEmail'
Here is code for account creation:
public async Task<AccountResponse> Register(RegisterRequest request)
{
if (await _dbContext.Accounts.AnyAsync(x => x.AccountEmail == request.Email.ToLower()))
// error appears here
throw new Exception("This e-mail address is already taken!");
var user = new User
{
Username = request.Username
};
var account = new Account
{
AccountEmail = request.Email,
HashedPassword = _passwordManager.HashPassword(request.Password),
DateOfBirth = request.DateOfBirth,
RegisterDate = DateTime.UtcNow,
User = user
};
user.Account = account;
_dbContext.Accounts.Add(account);
await _dbContext.SaveChangesAsync();
return new AccountResponse
{
Email = account.AccountEmail,
Username = user.Username,
Token = _tokenService.GenerateAccountToken(account.Id)
};
}
I have ensured that the column name AccountEmail is correctly spelled and matches in both the database schema and the entity class. I have also updated the database.
What could be causing this error, and how can I fix it?
DbContextis talking to the database you expect it to, and not an older schema that might be missing the column. Temporarily add the following line prior to attempting to read, with a breakpoint and check that the connection string is going to the expected database: `var connectionString = _dbContext.Database.GetDbConnection().ConnectionString;'