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.
3条答案
按热度按时间jjjwad0x1#
In your appsettings.json be sure to have this ConnectionString
And in Program.cs
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:
DbContext Class:
Connection String:
Server Name:
Database Name:
Program.cs:
Controller:
View:
Output:
Note: If you would like to know more details on Dbcontext configuration you could refer to this official document.
ycggw6v23#
I have to add "TrustServerCertificate=True;" to my Connection String