Mason.Chase
Mason.Chase

Reputation: 905

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`

When I'm trying to lookup a record by field name uuid I'm getting below error:

{"Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SyncBank.Models.XeroBankAccount]' to type 'SyncBank.Models.XeroBankAccount'

public XeroBankAccount FindAccountByUuid(String uuid)
        {
            try
            {
                using (SyncBankDbContext dbContext = new SyncBankDbContext())
                {
                    string tempUuid = uuid;
                    var result = (XeroBankAccount) dbContext.XeroBankAccounts.Where(x => x.AccountUuid == tempUuid);
                    return result;
                }
            }
            catch (Exception e)
            {
                string errorMessage = e.Message;
                return null;
            }
        }

Error:

{"Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SyncBank.Models.XeroBankAccount]' to type 'SyncBank.Models.XeroBankAccount'."}

XeroBankAccount.cs:

using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SyncBank.Xero;

namespace SyncBank.Models
{
    [Serializable]
    [Table("xero_bank_account")]
    public class XeroBankAccount
    {

        [Key]
        [Column("id")]
        public int Id { get; set; }

        [ForeignKey("XeroOrganisation")]
        [Column("organisation_id")]
        public int XeroOrganisationId { get; set; }

        public XeroOrganisation XeroOrganisation { get; set; }

        [Column("bank_id")]
        public int? BankId { get; set; }


        [Column("title")]
        [MinLength(1), MaxLength(128)]
        [Required]
        public String AccountTitle { get; set; }

        [Column("number")]
        [StringLength(50)]
        public String AccountNumber { get; set; }

        [Column("balance_statement")]
        public double? BalanceStatement { get; set; }

        [Column("balance_xero")]
        public double? BalanceXero { get; set; }

        [Column("last_statement_date")]
        public DateTime? LastStatementDate { get; set; }

        [Column("reconciled")]
        public BankAccountReconciled? Reconciled { get; set; }

        [Required]
        [Column("uuid")]
        [StringLength(256)]
        public string AccountUuid { get; set; }

        [Column("orders")]
        public int Orders { get; set; }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }

        public override bool Equals(Object obj)
        {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(obj is XeroBankAccount))
            {
                return false;
            }
            XeroBankAccount other = (XeroBankAccount)obj;
            return Id == other.Id;
        }

        public override String ToString()
        {
            return "org.syncbank.entity.XeroBankAccount[ accountId=" + Id + " ]";
        }
    }
}

SQL xero_bank_account:

CREATE TABLE `xero_bank_account` (
  `id` int(11) NOT NULL,
  `organisation_id` int(11) NOT NULL,
  `bank_id` int(11) DEFAULT NULL,
  `title` varchar(128) NOT NULL,
  `number` varchar(50) DEFAULT NULL,
  `balance_statement` decimal(12,2) DEFAULT NULL,
  `balance_xero` decimal(12,2) DEFAULT NULL,
  `reconciled` enum('true','false') NOT NULL DEFAULT 'false',
  `last_statement_date` datetime DEFAULT NULL,
  `uuid` varchar(256) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `orders` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `xero_bank_account`
--
ALTER TABLE `xero_bank_account`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `account_uuid` (`uuid`),
  ADD KEY `account_title_caption` (`number`),
  ADD KEY `bank_id` (`bank_id`);

Upvotes: 1

Views: 3647

Answers (1)

er-sho
er-sho

Reputation: 9771

You are trying to cast collection of XeroBankAccount to the single object of XeroBankAccount by using .Where() lambda expression so that's why you got an cast exception.

If you want to get your query must return single object of XeroBankAccount then, you can use any one of below

var result = (XeroBankAccount) dbContext.XeroBankAccounts.Where(x => x.AccountUuid == tempUuid).FirstOrDefault();

OR

var result = (XeroBankAccount) dbContext.XeroBankAccounts.FirstOrDefault(x => x.AccountUuid == tempUuid);

OR

var result = (XeroBankAccount) dbContext.XeroBankAccounts.Where(x => x.AccountUuid == tempUuid).Take(1).SingleOrDefault();

Upvotes: 5

Related Questions