ye-olde-dev
ye-olde-dev

Reputation: 1298

Invalid Object Name Error - EntityFrameworkCore 2.0

Howdee, I'm having an issue with entity framework telling me that the objects don't exist on my database when they do exist and I have mapped the names using the .ToTable method. Below is how I'm injecting the context into my controller:

In Startup.cs => ConfigureServices

var connection = @"Server={myserver};
                            Initial Catalog={mydb};Persist Security Info=False;
                            User ID={myId};Password={mypassword};MultipleActiveResultSets=False;
                            Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

services.AddDbContext<MyContext>(options => options.UseSqlServer(connection));

In MyController.cs

public class MyController : Controller
{
    [HttpPost("myroute")]
    public async Task<IActionResult> CreateUser([FromBody] MyUser myUser)
    {
        try
        {
            var user = _context.MyUser
                .Where(y => y.UserName == myUser.UserName)
                .FirstOrDefault();

            if (user != null)
            {
                var result = await _signInManager.UserManager.CreateAsync(myUser);

                if (result.Succeeded) return Ok();
            }
        }
        catch (Exception ex)
        {

            _logger.LogError($"Create User Error: {ex}");
        }

        return BadRequest();
    }
}

In MyContext.cs

public class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options)
        : base(options)
    {

    }
    public DbSet<MyApi.DataAccess.Entities.MyUser> MyUser { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<MyApi.DataAccess.Entities.MyUser>()
            .ToTable("dbo.MyUsers");
    }
}

This is my first time getting into asynchronous programming in server side code so there's a chance it could be something there? I've tested the connection string in a console application and I'm able to connect to the database via the console application (C# .Net) so I'm assuming that it is not the issue (Plus, I grabbed the connection string straight from Azure). Thanks in advance for the help!

Upvotes: 4

Views: 6117

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205799

In EF (Core) configuration (both data annotations and fluent API), the table name is separated from the schema.

Remove the "dbo." from the table name and use the ToTable overload with name and schema arguments:

.ToTable("MyUsers", "dbo");

Or taking into account that dbo is the default schema (if not configured differently), simply:

.ToTable("MyUsers");

As it is currently, it considers table dbo.dbo.MyUsers which of course does not exist.

Upvotes: 9

Related Questions