简体   繁体   中英

How to setup Entity Framework in ASP.NET Core project

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM