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 question is I have 2 table one is User table the other one is CustomerUsers I select them by Deleted=0 When I try to list all users and have customerId, I am having issue that sequence contains no matching element error
My Code is below any help would be appriciate

Thank you

My Dapper query is below :

 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

Issue generally occurs if your lookUp.First(m => m.UserId == u.UserId) didnt return any results.

You can use FirstOrDefault something like below instead of First which returns null (default value) if it didnt find any results for matching criteria.

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

Not sure why you are checking against lookUp, Its a new list that you created just before connecting to DB. It will always be empty (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