我有一个新的ASP.NET核心项目,我试图简单地查询数据库并在页面上显示查询结果。我是使用ASP.NET Core的新手,并且从研究中发现最好使用Entity Framework来查询数据库。
我试图关注this guide以了解如何通过实体框架连接到数据库,但指南中有一个步骤引用了一个名为project.json
的文件,行:"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
应该添加。
问题是这个文件在Visual Studio 2017项目中不存在,如this guide中所确认的那样,我在项目中的任何地方都看不到.csproj文件。 project.json
的替代品。
这个.csproj
文件是否应该在项目创建后创建?在Visual Studio 2017中的ASP.NET Core项目中通过Entity Framework建立与数据库的连接的实际过程是什么?
答案 0 :(得分:1)
当我学习如何创建ASP.NET Core项目时,我的老师建议我们从MS文档中遵循此guide。我建议您按照该指南解决您的问题。在该指南中,您需要将数据库的连接字符串添加到项目主文件夹中的文件appsettings.json
。连接字符串是这样的:
"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabaseName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
然后将该连接字符串添加到文件
appsettings.json
,就像这样:"ConnectionStrings": { "DB_String": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabaseName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" },
然后,您必须通过添加以下行来更改项目主文件夹中
ConfigureServices
文件的Startup.cs
方法:services.AddDbContext<yourContextClass>(options => options.UseSqlServer(Configuration.GetConnectionString("DB_String")));
然后该方法将如下所示:
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<yourContextClass>(options => options.UseSqlServer(Configuration.GetConnectionString("DB_String"))); services.AddMvc(); }
这是通过使用SQL Server客户端与ASP.NET Core 2配置与Entity Framework的数据库连接的步骤。对于接下来的步骤,我建议您按照guide进行操作。
答案 1 :(得分: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")));
}
最后,您可以在模型类库下使用代码优先方法。