7

I have developed asp .net core wep api 2.0 application with EntityFrameworkCore.SqlServer 2.0. It is developed using database first approach. When trying to access entities using dbcontext application is going to break mode. I cannot find the reason for application state to going break state. Please help to resolve this.

Below is the OnConfiguring method in DBContext class.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;");
        }
    }

Below code block used to access dbcontext entities in controller

    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        VotingAppDBContext context = new VotingAppDBContext();
        var questions = context.Questions.ToList();
        return new string[] { "value1", "value2" };
    }

Installed packages

Application error

5
  • I have the exact issue. I have no idea how to fix it so far. Commented Sep 21, 2017 at 14:52
  • so... does your database has schemas? When I removed my schemas and then scaffolded it started working. Commented Sep 21, 2017 at 15:34
  • I found my issue. I used VARCHAR(max) to define the column length.Somehow EF doesnt understand that and silently fails Commented Sep 21, 2017 at 18:50
  • 1
    Ok it ended being that I did a self refencing key to PrimaryKey incorrectly. Instead of throwing an error and telling me what it was it just did app break mode. Basically double check ur schema table by table and determine where u made an critical error. Commented Sep 22, 2017 at 15:19
  • Thank you very much. That's the reason. My schema also has self referencing primary key. When I remove that it works without errors. I don't know why visual studio behaves that way, it's not user friendly. Are there any techniques to trace these kind of issues? Commented Sep 23, 2017 at 8:09

3 Answers 3

2

1.- First of all you shouldn't create a context inside the controller, avoid use 'new' with dependencies because that would make your code untestable, in my case as I use UnitOfWork I inject it as IUnitOfWork instance that is, indeed, an extension of MyConext, and you'd inject it within the StartUp class... To do so I have a private method (to perform this in a single private call) that looks like:

 private void AddEntityFrameworkAndDbContext(IServiceCollection services)
        {
            services.AddEntityFrameworkSqlServer();

            var migrationsAssemblyName = typeof(MyContext).GetTypeInfo().Assembly.GetName().Name;
            services.AddDbContext<MyContext>(options =>
            {
                options.UseSqlServer(
                    "MY CONNECTION STRING GOES HERE (BUT I RETREIVE IT FROM ANOTHER SERVICE)",
                    sqlServerOptionsAction: sqlOptions =>
                    {
                        sqlOptions.MigrationsAssembly(migrationsAssemblyName);
                        sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                    });
            },
            ServiceLifetime.Scoped  // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   ).AddUnitOfWork<MyContext>(); // This is because I'm also using EF Core Unit of work NuGet Package
        }

I'm calling that private method from ConfigureServices(IServiceCollection services), as I said, in StartUp class

        // Add EF, and UoW
        AddEntityFrameworkAndDbContext(services);

2.- Secondly (but I'd say that this is your real problem) I'd say that you missed base.OnConfiguring(options); in your context, it should be like:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;");
        }
        base.OnConfiguring(optionsBuilder);
    }

Also, please, take a look at this answer I wrote few weeks ago: How to setup EF6 Migrations with ASP.NET Core

In addition, that UnitOfWork project deserves a reading, take a look at it here: https://github.com/arch/UnitOfWork

I hope it helps,

Juan

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure if the issue still exists. I've had the same issue today. The fix was to update all nuget packages (in my case, Microsoft.Extensions.Configuration, etc) to the latest version.

1 Comment

In my case, it is due to self referencing primary key. When I removed that reference, it worked.
-1

This occurs when you have self referencing primary key in your schema. Using sql server database diagram you can view that graphically. you have to remove that reference in order to solve this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.