Search code examples
c#databaseentity-frameworklinq

{"Unable to cast object of type 'System.String' to type 'System.Guid'."} System.InvalidCastException


This is the method in my service.

public async Task<InvitedUser> CheckEmail(string Email)
{
    var result = await _db.InvitedUser.SingleOrDefaultAsync(_ => _.Email == Email);
    return result;
}

The schema for Invited User is :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Project.Core.Entities
{
    [Table("InvitedUser")]
    public class InvitedUser
    {
        [Key]
        public Guid UserAccountId { get ; set; }
        public string Email { get; set; }
        public Guid ReferrerAccountId { get ; set; }    
        public string Name { get; set; }    
        public string AccessCode { get; set; }
        public string Status { get; set; }
        public DateTime CreatedAt { get; set; }         
    }
}

Now whenever I execute this above mentioned LINQ query it gives this error

{"Unable to cast object of type 'System.String' to type 'System.Guid'."}

I've also tried

var result = _db.InvitedUser.Where(i => i.Email== Email)=.FirstOrDefault()

Still no progess.

EF Verison: 5.0.9 C# Version: 3.1


Solution

  • Your ReferrerAccountId and UserAccountId field types are 'varchar' which is string. But your properties in the model has Guid type.

    So You should either save the string fields in the table as uniqeidentifier type or define them as string in your model(instead of Guid).