context.SaveChanges() method is not saving data in database

Viewed 48

I am new to Dotnet and EF. I trying to learn EF. So, I created a to-do app using ASP.NET CORE Web app. Basically it is a Razor page application. I created another Class library project for working with EF. I added the reference to the first project. It is a combination of ASP.NET CORE with EF. here is the DbContext file.

namespace TaskMaster_DataLayer.Models
{
    public class TmDbContext : DbContext
    {
        public TmDbContext() : base()
        {

        }
        public DbSet<Status> Statuses { get; set; }
        public DbSet<Task> Tasks { get; set; }
        
    }
}

And here is the index.cshtml.cs file.

namespace TaskMaster.Pages
{
    [BindProperties]
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly TmDbContext taskMasterContext;
        
        public List<Status> stsList;

        public Task? task = null;
        public string? TaskValue { get; set; }
        public DateTime? DueDate { get; set; }
        public string? StatusName { get; set; }
        public Status status { get; set; }


        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
            taskMasterContext = new TmDbContext();
            stsList = taskMasterContext.Statuses.ToList();
        }

        public void OnGet()
        {
        }

        public void OnPost()
        {
            TaskValue = Request.Form["Task"];
            if(TaskValue != null && TaskValue != String.Empty)
            {
                foreach(var sts in stsList)
                {
                    var name = sts.GetName();
                    if(name == StatusName)
                    {
                        status = sts;
                        break;
                    }
                }
                task = new Task()
                {
                    Name = TaskValue,
                    DueDate = DueDate,
                    StatusId = status.Id,
                    status = status,
                };
                taskMasterContext.Tasks.Add(task);
                taskMasterContext.SaveChanges();
            }
        }
    }
}

When Submiting the form the OnPost method is executing. I didn't get any errors but the data is not saving or inserting to the database. The task is added to the DbSet but SaveChanges method is not working. I don't know what I am missing.

anyone help me out. I got so frustrated.

1 Answers

Hope this helps you, if you follow the process this will work.

From what you have mentioned you have 2 projects first Asp dotnet core and second ClassLibrary to handle your EfCore.

Now First Goto your Asp proj and open appsettings.json file and add connection string as under:

"ConnectionStrings": {
"defaultCon": "Server= 
(localdb)\\MSSQLLocalDB;Database=TodoDB;Trusted_Connection=True;"
}

(you can update your server name if your using SQLEXPRESS you can updated accordingly) Connection String Screenshot

Looking at your models i have created as below two just for example in Class Library:

public class Task
{
  [Key]
  public int Id { get; set; }
  public string TaskName { get; set; }
  public Status Status { get; set; }
}

public class Status
{
   public int Id { get; set; }
   public int TaskId { get; set; }
   public bool status { get; set; }
}

Your DbContext Should be like:

public class AppDbContext : DbContext
{
  public AppDbContext(DbContextOptions<AppDbContext> options): base(options)
  {

  }

  public DbSet<Status> Statuses { get; set; }
  public DbSet<Task> Tasks { get; set; }

}

Now we have to register AppDbContext in Dependency Injection for that Create class in ClassLibrary proj as below.

public static class ServiceRegistration
{
        public static IServiceCollection AddEFServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(configuration.GetConnectionString("defaultCon")));
            return services;
        }
}

In Asp proj open startup class and add the extention method we created AddEFServices passing in the Configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddEFServices(Configuration);
}

For this example i have used Dotnet Core 5, Install the below Nuget packages in Class Library:

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.17">
and for Asp proj Install below Nuget Package:
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.17">

Now Open 'Package manager console' you can find under(Tools/Nuget Package Manager/Package manager console) Keep your Asp project as startup Proj and in Package manager console Window Default Project Should be your ClassLibrary

Type Below Command: Add-Migration InnitialSetup (If you dont get any errors a migrations class will be created next do below) Update-Database (Your Database and tables will be created)

Now Goto your Asp Razor page (IndexModel) Now in the Constructor you have access to the AppDbContext do as under:

private readonly ILogger<IndexModel> _logger;
    private readonly AppDbContext _dbContext;

public IndexModel(ILogger<IndexModel> logger, AppDbContext dbContext)
{
    _logger = logger;
    _dbContext = dbContext;
} 

//For Sample i have hardcoded the data in your case you can receive the data from HTML Form.        
public void OnGet()
{
      var NewTast = new ClassLibrary.Model.Task();
      NewTast.TaskName = "Test Task";
      var Status = new Status();
      Status.status = true;
      NewTast.Status = Status;

      _dbContext.Tasks.Add(NewTast);
      _dbContext.SaveChanges();
}

Now when you check your Database you can see that Table Statuses and Table Tasks will have data inserted in them.

Related