繁体   English   中英

如何修复'InvalidCastException:无法将类型为'System.Int32'的对象转换为类型为'System.String'的对象

[英]How can I fix the 'InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'

从我的mysql数据库中检索数据时,出现上述错误消息。

该方法可以与其他表(例如“用户”)一起正常使用,但是,我没有看到为什么它也不能与客户端表一起工作的问题。

客户实体:

public class Client : IEntity<int>
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public string Name { get; set; }

        public Entities Entity { get; set; }

        public ICollection<ClientBusinessSector> Client_Business_Sectors{ get; set; }
            = new List<ClientBusinessSector>();

        [ForeignKey("Country_Id")]
        public Country Country { get; set; }
        public int Country_Id { get; set; }

        [ForeignKey("City_Id")]
        public City City { get; set; }
        public int City_Id { get; set; }

        public string Address { get; set; }

        public ICollection<ClientUser> Client_Users { get; set; }
            = new List<ClientUser>();

        public ICollection<ClientService> Client_Services { get; set; }
            = new List<ClientService>();

        public enum Entities
        {
            GmbH = 1,
            AG,
            Einzelfirma,
            Kollektivgesellschaft,
            Genossenschaft
        }
    }

控制器级别:

[HttpGet()]
    public async Task<IActionResult> GetAllClients()
    {
        var clientsFromRepo = await _clientRepository.GetAllAsync();
        var clients = Mapper.Map<IEnumerable<ClientDto>>(clientsFromRepo);

        return Ok(clients);
    }

从控制器调用的存储库方法:

public async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await _context.Set<TEntity>()
                .ToListAsync();
        }

我需要从数据库中获取客户列表。 即使它是一个空列表,它也应返回200 OK状态。 存储库方法可以与其他表一起正常工作,但是由于某种原因不能与客户端表一起工作

我收到的错误消息: InvalidCastException:无法将类型为'System.Int32'的对象强制转换为类型为'System.String'。

我刚发现错误:我的DbContext中有一个modelbuilder。

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Client>()
            .Property(c => c.Entity)
            .HasConversion<string>();
    }

拿出来,它应该正常工作:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM