英文:
Server connection problem in ASP.NET Core MVC
问题
我有一个关于我的ASP.NET Core MVC应用程序的问题。我创建了一个SQL Server数据库实例,以及一个与我的模型类同名且具有相同字段的表格。
我还创建了一个DbContext
类,并编写了一个连接字符串。
我的问题是我无法连接到服务器,也无法在服务器上保存用户数据。
我的控制器(当我调用database.SaveChanges()
时,我在这个类中遇到错误):
public class RegistrationController : Controller
{
private readonly DataBaseContext dataBaseContext;
public RegistrationController(DataBaseContext databaseContext)
{
this.dataBaseContext = databaseContext;
}
public IActionResult Index()
{
return View();
}
public IActionResult Registration(User user)
{
dataBaseContext.User.Add(user);
dataBaseContext.SaveChanges();
return RedirectToAction("Index");
}
}
我的DbContext
:
public class DataBaseContext: DbContext
{
public DataBaseContext(DbContextOptions options): base(options)
{
}
public DbSet<User> User { get; set; }
}
我的连接字符串:
builder.Services.AddDbContext<DataBaseContext>(x => x.UseSqlServer("Server=localhost;Database=OnlineShop;Integrated Security=True;"));
我找不到解决方法。
英文:
I have a problem with my ASP.NET Core MVC application. I created a SQL Server database instance, and a table that has the same name as my model class and its fields.
I also created a DbContext
class. And I also wrote a connection string.
My problem is that I cannot connect to the server and I cannot save user data in the server.
My controller (I get an error in this class when I call database.SaveChanges()
):
public class RegistrationController : Controller
{
private readonly DataBaseContext dataBaseContext;
public RegistrationController(DataBaseContext databaseContext)
{
this.dataBaseContext = databaseContext;
}
public IActionResult Index()
{
return View();
}
public IActionResult Registration(User user)
{
dataBaseContext.User.Add(user);
dataBaseContext.SaveChanges();
return RedirectToAction("Index");
}
}
My DbContext
:
public class DataBaseContext:DbContext
{
public DataBaseContext(DbContextOptions options):base(options)
{
}
public DbSet<User> User { get; set; }
}
My connection string:
builder.Services.AddDbContext<DataBaseContext>(x => x.UseSqlServer("Server=localhost;Database=OnlineShop;Integrated Security=True;"));
I cannot find a solution.
答案1
得分: 0
在您的appsettings.json中,请确保有以下连接字符串:
"ConnectionStrings": {
"MyDbContext": "Server=localhost;Database=OnlineShop;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=true"
}
以及在Program.cs中:
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbContext")));
英文:
In your appsettings.json be sure to have this ConnectionString
"ConnectionStrings": {
"MyDbContext": "Server=localhost;Database=OnlineShop;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=true"
}
And in Program.cs
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbContext")));
答案2
得分: 0
以下是您要翻译的内容:
我的问题是我无法连接到服务器,也无法保存用户数据在服务器上。我的控制器(当我调用database.SaveChanges()时出错):
可能是数据实体定义或连接字符串不正确,导致了这个问题。如果您能分享一下您的连接字符串是如何编写的,会更好。不过,您可以参考以下示例和步骤:
用户模型:
public class User
{
[Key]
public long UserId { get; set; }
public string? UserName { get; set; }
public string? UserEmail { get; set; }
public string? LoginId { get; set; }
public string? Password { get; set; }
}
DbContext 类:
public class DataBaseContext : DbContext
{
public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("TestUsers");
}
}
连接字符串:
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Program.cs:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataBaseContext>(x => x.UseSqlServer(connectionString));
控制器:
public class RegistrationController : Controller
{
private readonly DataBaseContext dataBaseContext;
public RegistrationController(DataBaseContext databaseContext)
{
this.dataBaseContext = databaseContext;
}
public IActionResult Index()
{
var listUsers = dataBaseContext.Users.ToList();
return View(listUsers);
}
public IActionResult Create()
{
return View();
}
public IActionResult Registration(User user)
{
dataBaseContext.Users.Add(user);
dataBaseContext.SaveChanges();
return RedirectToAction("Index");
}
}
视图:
@model RegistrationServerApp.Models.User
@{
ViewData["Title"] = "Create";
}
<h1>Register</h1>
<div class="row">
<div class="col-md-4">
<form asp-action="Registration">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<!-- 其他输入字段 -->
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
注意: 如果您想了解更多有关 DbContext 配置的详细信息,可以参考此官方文档。
英文:
> My problem is that I cannot connect to the server and I cannot save
> user data in the server. My controller (I get an error in this class
> when I call database.SaveChanges()):
You may have incorrct data entity defination or connecting string which causing the issue. It would be nicer if you could share how have your been written your conncetion string. However, you can refer the sample and steps below:
User Model:
<!-- language: c# -->
public class User
{
[Key]
public long UserId { get; set; }
public string? UserName { get; set; }
public string? UserEmail { get; set; }
public string? LoginId { get; set; }
public string? Password { get; set; }
}
DbContext Class:
<!-- language: c# -->
public class DataBaseContext : DbContext
{
public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("TestUsers");
}
}
Connection String:
<!-- language: c# -->
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
},
Server Name:
Database Name:
Program.cs:
<!-- language: c# -->
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataBaseContext>(x => x.UseSqlServer(connectionString));
Controller:
<!-- language: c# -->
public class RegistrationController : Controller
{
private readonly DataBaseContext dataBaseContext;
public RegistrationController(DataBaseContext databaseContext)
{
this.dataBaseContext = databaseContext;
}
public IActionResult Index()
{
var listUsers = dataBaseContext.Users.ToList();
return View(listUsers);
}
public IActionResult Create()
{
return View();
}
public IActionResult Registration(User user)
{
dataBaseContext.Users.Add(user);
dataBaseContext.SaveChanges();
return RedirectToAction("Index");
}
}
View:
<!-- language: c# -->
@model RegistrationServerApp.Models.User
@{
ViewData["Title"] = "Create";
}
<h1>Register</h1>
<div class="row">
<div class="col-md-4">
<form asp-action="Registration">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="UserEmail" class="control-label"></label>
<input asp-for="UserEmail" type="email" class="form-control" />
<span asp-validation-for="UserEmail" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LoginId" class="control-label"></label>
<input asp-for="LoginId" class="form-control" />
<span asp-validation-for="LoginId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" type="password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
Output:
Note: If you would like to know more details on Dbcontext configuration you could refer to this official document.
答案3
得分: 0
"TrustServerCertificate=True;" 需要添加到我的连接字符串中。
英文:
I have to add "TrustServerCertificate=True;" to my Connection String
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论