I'm trying to use ASP.NET Core 5 to create a to do list and I"m trying to incorporate my seed data.
This is my model class:
using Microsoft.AspNetCore.Components.Forms;
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace To_Do_List.Models
{
public class To_Do
{
public int Id { get; set; }
// Setting requirements for attributes as shown below:
[StringLength(60, MinimumLength=3)]
[RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Title must begin with a capital letter and be a minimum 3 characters long with a maximum of 60 characters.")] // Requires first letter to be a capital letter, allows other text to be written afterwards, \s matches any whitespace characters
[Required] // Indicates property must have a value
public string? Title { get; set; }
[StringLength(60, MinimumLength = 3)]
[Required]
public string? Description { get; set; }
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[Display(Name = "End Date")]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
[Display(Name = "Priority")]
public int priority { get; set; }
[Display(Name = "Completed?")]
public bool checkbox { get; set; }
}
}
And this is my seeddata.cs
file:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using To_Do_List.Data;
using System;
using System.Linq;
using To_Do_List.Models;
namespace To_Do_List.Models;
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new To_Do_ListContext(
serviceProvider.GetRequiredService<
DbContextOptions<To_Do_ListContext>>()))
{
// Look for any tasks
if (context.To_Do.Any())
{
return; // DB has been seeded
}
context.To_Do.AddRange(
new To_Do
{
Title = "test",
Description = "this is a test",
StartDate = DateTime.Parse("2023-4-22"),
EndDate = DateTime.Parse("2023-4-28"),
checkbox = true,
priority = 3
}
);
context.SaveChanges();
}
}
}
However, I'm getting an error:
InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'
I'm fairly certain it's my priority variable that is having an issue since converting the type of priority to a string and changing the seed data accordingly allows the application to work.
I appreciate any help for this issue.
Oh wait I found out the issue. I forgot to migrate the database to the new data types above.
This can be done by editing the database via the Nuget package manager and typing:
Add-Migration migration_name
Update-Database
Such that migration_name is the name of the new migration.