SQL Server Server connection problem in ASP.NET Core MVC

sdnqo3pr  于 2023-06-21  发布在  .NET
关注(0)|答案(3)|浏览(137)

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.

jjjwad0x

jjjwad0x1#

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

deyfvvtc2#

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:

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:

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:

"ConnectionStrings": {
    "DefaultConnection": "Server=YourServerName;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

Server Name:

Database Name:

Program.cs:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataBaseContext>(x => x.UseSqlServer(connectionString));

Controller:

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:

@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.

ycggw6v2

ycggw6v23#

I have to add "TrustServerCertificate=True;" to my Connection String

相关问题