Server connection problem in ASP.NET Core MVC

huangapple go评论99阅读模式
英文:

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(&quot;Index&quot;);
    }
}

My DbContext:

public class DataBaseContext:DbContext
{
    public DataBaseContext(DbContextOptions options):base(options)
    {
    }

    public DbSet&lt;User&gt; User { get; set; }
}

My connection string:

builder.Services.AddDbContext&lt;DataBaseContext&gt;(x =&gt; x.UseSqlServer(&quot;Server=localhost;Database=OnlineShop;Integrated Security=True;&quot;));

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

&quot;ConnectionStrings&quot;: {
  &quot;MyDbContext&quot;: &quot;Server=localhost;Database=OnlineShop;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=true&quot;
}

And in Program.cs

builder.Services.AddDbContext&lt;MvcMovieContext&gt;(options =&gt;
    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;MyDbContext&quot;)));

答案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"
}

服务器名称:
Server connection problem in ASP.NET Core MVC

数据库名称:
Server connection problem in ASP.NET Core MVC

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");
    }
}

输出:
Server connection problem in ASP.NET Core MVC

注意: 如果您想了解更多有关 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&lt;DataBaseContext&gt; options) : base(options)
        {
           
        }
        public DbSet&lt;User&gt; Users { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           
            modelBuilder.Entity&lt;User&gt;().ToTable(&quot;TestUsers&quot;);
           

        }
    }

Connection String:

<!-- language: c# -->
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
},

Server Name:

Server connection problem in ASP.NET Core MVC

Database Name:

Server connection problem in ASP.NET Core MVC

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(&quot;Index&quot;);
        }
    }

View:

<!-- language: c# -->
@model RegistrationServerApp.Models.User

@{
    ViewData[&quot;Title&quot;] = &quot;Create&quot;;
}

&lt;h1&gt;Register&lt;/h1&gt;
&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;form asp-action=&quot;Registration&quot;&gt;
            &lt;div asp-validation-summary=&quot;ModelOnly&quot; class=&quot;text-danger&quot;&gt;&lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label asp-for=&quot;UserName&quot; class=&quot;control-label&quot;&gt;&lt;/label&gt;
                &lt;input asp-for=&quot;UserName&quot; class=&quot;form-control&quot; /&gt;
                &lt;span asp-validation-for=&quot;UserName&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
            &lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label asp-for=&quot;UserEmail&quot; class=&quot;control-label&quot;&gt;&lt;/label&gt;
                &lt;input asp-for=&quot;UserEmail&quot; type=&quot;email&quot; class=&quot;form-control&quot; /&gt;
                &lt;span asp-validation-for=&quot;UserEmail&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
            &lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label asp-for=&quot;LoginId&quot; class=&quot;control-label&quot;&gt;&lt;/label&gt;
                &lt;input asp-for=&quot;LoginId&quot; class=&quot;form-control&quot; /&gt;
                &lt;span asp-validation-for=&quot;LoginId&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
            &lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label asp-for=&quot;Password&quot; class=&quot;control-label&quot;&gt;&lt;/label&gt;
                &lt;input asp-for=&quot;Password&quot; type=&quot;password&quot; class=&quot;form-control&quot; /&gt;
                &lt;span asp-validation-for=&quot;Password&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
            &lt;/div&gt;
           
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;input type=&quot;submit&quot; value=&quot;Create&quot; class=&quot;btn btn-primary&quot; /&gt;
            &lt;/div&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/div&gt;


&lt;div&gt;
    &lt;a asp-action=&quot;Index&quot;&gt;Back to List&lt;/a&gt;
&lt;/div&gt;

@section Scripts {
    @{
        await Html.RenderPartialAsync(&quot;_ValidationScriptsPartial&quot;);
    }
    }

Output:

Server connection problem in ASP.NET Core MVC

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

huangapple
  • 本文由 发表于 2023年6月8日 01:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定