How to setup Entity Framework in ASP.NET Core project

老子叫甜甜 提交于 2019-12-11 10:10:24

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49972121/how-to-setup-entity-framework-in-asp-net-core-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!