1

I have a new ASP.NET Core project where I am trying to simply query a database and display results of the query on a page. I'm new to using ASP.NET Core and have found from researching that it would be best to use Entity Framework in order to query the database.

I was trying to follow this guide in order to figure out how to connect to the database via the Entity Framework, but there is a step in the guide that references a file called project.json to which the line: "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", should be added.

The problem is that this file doesn't exist in Visual Studio 2017 projects as is confirmed in this guide and I don't see the .csproj file anywhere in my project that the article references as the replacement for project.json.

Is this .csproj file supposed to be created after the project has already been created? What is the actual process for setting up a connection to a database via the Entity Framework in an ASP.NET Core project within Visual Studio 2017?

1
  • That guide is very old and references an old version of .Net Core that has been abandoned long ago. Try here instead learn.microsoft.com/en-us/ef/core Commented Apr 23, 2018 at 1:10

2 Answers 2

1

appsettings.json

"ConnectionStrings": {
    "Cn": "Server=(localdb);Database=TestDB;Persist Security Info=True;User ID=sa;Password=abcd123!"
  }

DbContext

public TestDbContext:DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> option) : base(option)
    {

    }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
    {
         relationship.DeleteBehavior = DeleteBehavior.Restrict;
    }
    base.OnModelCreating(modelBuilder);
}

public DbSet<Users> Users { get; set; }

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
        services.AddDbContext<TestDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("Cn")));
}

Finally, you can work with code first approach, under your model class library.

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

3 Comments

Which file does the db context need to be created in and is that all that is needed?
@loremIpsum1771 under Model folder you can create TestDbContext. this tutorial site could help you: entityframeworktutorial.net/efcore/entity-framework-core.aspx
Thanks for the link. It provided information on how to derive models from existing tables
1

When I was learning how to create a ASP.NET Core project, my teacher suggested us to follow this guide from the MS docs. I suggest you to follow that guide to solve your problem. In that guide says that you need to add the connection string of your database to the file appsettings.json that's located in your projects main folder. The connection string is like this:

"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabaseName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"

And you add that connection string to the file appsettings.json, just like this:

"ConnectionStrings": {
"DB_String": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabaseName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},

Then you have to change the ConfigureServices method at the Startup.cs file in your project main folder by adding the following line:

services.AddDbContext<yourContextClass>(options => options.UseSqlServer(Configuration.GetConnectionString("DB_String")));

And then the method will seen like this:

public void ConfigureServices(IServiceCollection services)
   {
       services.AddDbContext<yourContextClass>(options => options.UseSqlServer(Configuration.GetConnectionString("DB_String")));
       services.AddMvc();
   }

That are the steps to configurate with ASP.NET Core 2 a database connection with Entity Framework by using the SQL Server client. For the next steps I suggest you to follow this guide.

6 Comments

Where does the Biblioteca_Context come from?
It comes frontera a example exercise that I've made... Excuse me, I changed that...
Where is the context class supposed to be defined?
@loremIpsum1771 The Context is supposed to be defined in another source file of your project. The Context class inherits from DbContext class, which is contained in the System.Data.Entity namespace. Here is the DbContext class definition at Microsoft MSDN: msdn.microsoft.com/en-us/library/…
So I just need to add another class called yourContextClass (in this case) to the root of the VS project?
|

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.