Home > other >  Why do not my LINQ query print out data from the database?
Why do not my LINQ query print out data from the database?

Time:01-16

I have two separate classes. Login and UserContent. I want that if you enter your personal number, you should "log in". Then you should be able to get data out.

I pass number to BankContent method. There I want to get the name from the user, however when I write I only get this message to the console. Welcome! Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String] So I do not get the name of the user. Does anyone know why?

Login class

public class Login : ILogin
    {
        private readonly UserContent _userContent;
        private readonly ApplicationDbContext _db;

        public Login(UserContent userContent, ApplicationDbContext db)
        {
            _userContent = userContent;
            _db = db;
        }

       public void Enter()
        {
            Console.WriteLine("Enter your Social Number to login");
            var number = Convert.ToInt32(Console.ReadLine());
            var result = _db.Customers.Where(x => x.SocialNumber == number).Any();
            
            if (_db == null)
            {
                Console.WriteLine($"No customer with {number} was found");
                return;
            }
            if (result == true)
            {
               
                _userContent.BankContent(number);
            }
            else
            {
                Console.WriteLine($"No customer with {number} was found!");
            }


          
        }
    }

UserContent with BankContent Method

  public class UserContent : IUserContent
    {
        private readonly ApplicationDbContext _db;

        public UserContent(ApplicationDbContext db)
        {
            _db = db;
        }

        public void BankContent(int number)
        {
            var name = _db.Customers.Where(z => z.SocialNumber == number).Select(x => x.FirstName);

            Console.WriteLine("Welcome! "   name);
        }
    }

CodePudding user response:

The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.

So in your case:

var name = _db.Customers.Where(z => z.SocialNumber == number).Select(x => x.FirstName).FirstOrDefault();

Using the FirstorDefault() method will return the first element of your sequence or a default value if element isn't there.

  •  Tags:  
  • Related