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