Search code examples
c#sqlentity-frameworkasp.net-mvc-5

Unable to cast object of type 'System.Data.Entity.DynamicProxies.ApplicationUser_xxxxxxxx' to type 'System.String'


I am trying to save the data into database using below ActionResult

public ActionResult Create(GigFormViewModel viewModel)
    {
        var artistId = User.Identity.GetUserId();
        var artist = _context.Users.Single(u => u.Id == artistId);
        var genre = _context.Genres.Single(g => g.Id == viewModel.Genre);
        var gig = new Gig
        {
            Artist = artist,
            DateTime = DateTime.Parse(string.Format("{0} {1}", viewModel.Date, viewModel.Time)),
            Genre=genre,
            Venue=viewModel.Venue
        };
        _context.Gigs.Add(gig);
        _context.SaveChanges();
        return RedirectToAction("Index", "Home");

    }

While Saving the data, I am getting error

Unable to cast object of type 'System.Data.Entity.DynamicProxies.ApplicationUser_C811B05818B5E64ECDA3F7F75CC04ED97BE32CA9226F31FEEEF1EE499B74428B' to type 'System.String'.

Below is the screenshot for more details: enter image description here

Models:

public class Genre
{
    public byte Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }
}

public class Gig
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public ApplicationUser Artist { get; set; }

    [Required]
    public DateTime DateTime { get; set; }

    [Required]
    public string Venue { get; set; }

    [Required]
    public Genre Genre { get; set; }
}

What could be the issue??


Solution

  • Figured it out myself. I think it was issue with Gigs Model and validation of Artist. Removed Data Annotation [StringLength(255)] and it worked fine.

    So updated Gigs Model class is as below:

    public class Gig
     {
    public int Id { get; set; }
    
    [Required]
    [StringLength(255)]
    public ApplicationUser Artist { get; set; }
    
    [Required]
    public DateTime DateTime { get; set; }
    
    [Required]
    public string Venue { get; set; }
    
    [Required]
    public Genre Genre { get; set; }
    }