When I execute my sp GetAllUsers in Dapper, why do I get a sequence contains no matching element error?

.net c# dapper entity-framework model-view-controller

Question

Hello, my query is: I have two tables: CustomerUsers and User Table. I pick them by Deleted=0. The sequence includes no matching element problem occurs when I attempt to list all users with customerId.
Any assistance would be appreciated. My code is below.

Many thanks

I'll put my Dapper remark here:

 public List<User> GetAllUsers()
        {
            List<User> user = new List<User>();

            try
            {
                //var sql = @"SELECT * FROM [User] WHERE Deleted=0";

                var sql = @"SELECT * from [User] u LEFT JOIN  [CustomerUser] cu ON u.UserId = cu.CustomerUserId  WHERE u.Deleted=0";

                var lookUp = new List<User>();

                using (var cn = Settings.Helper.ConnectionStringBiz())
                {
                    cn.Open();

                    cn.Query<User,Customer,User>(sql,(u,c)=>
                    {
                        var myUser = lookUp.First(m => m.UserId == u.UserId);

                        if (myUser == null)
                        {
                            lookUp.Add(u);

                            myUser = u;
                        }

                        myUser.Customer = c;

                        return null;

                    },splitOn:"CustomerId");
                }

                return lookUp;
            }

            catch (Exception ex) 
            {
                return user;
            }
        }
1
1
2/16/2018 8:18:55 AM

Accepted Answer

Problems often arise if yourlookUp.First(m => m.UserId == u.UserId) not provide any results.

You may utilizeFirstOrDefault Instead of First, which returns null (the default value) if no results matched the search criteria, use something similar to the following.

var myUser = lookUp.FirstOrDefault(m => m.UserId == u.UserId);

It's a fresh list that you constructed just before joining to the database, thus I'm not sure why you are verifying against lookUp. It will always remain bare (If I am not understanding it wrong).

3
2/16/2018 8:23:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow