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.