首页 > 解决方案 > How to use GetById function in c#

问题描述

I am learning c#. I am trying to create a basic list in a mock repository (Rather than jumping into pulling data from SQL straight away). I have a list that contains cars and has fields such as Id, Model, Make, description etc.

I am then trying to create a method in my Car.CS class, of which gets the car by Id. For example if i pass in the ID of the car, it will return the other details of the car.

Unfortunately when i run the console application, it just returns blank in the console? Could someone let me know where i'm going wrong please?

First of all i have an ICarRepository

namespace GeneralConsoleApp
{
    interface ICarRepository
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}

and then i have my MockCarRepository of which contains the list

namespace GeneralConsoleApp
{
    class MockCarRepository : ICarRepository
    {
        public IEnumerable<Car> Cars =>
            new List<Car>
            {
                new Car {Id = 1, Name="BMW", Price=23000.00M, Description="BMW car" }
            };

        public int Id { get; set; }
        public string Name {get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}

Next is my Car.cs

namespace GeneralConsoleApp
{
    class Car
    {
        private readonly List<Car> CarList = new List<Car>();

        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }

        public Car GetCarById(int Id)
        {
            return CarList.FirstOrDefault(z => z.Id == Id);

        }
    }
}

And finally my program.cs main method

namespace GeneralConsoleApp
{
    class Program
    {

        static void Main()
        {
            Car car = new Car();


            Console.WriteLine(car.GetCarById(1));

            Console.ReadLine();
        }
    }
}

标签: c#

解决方案


Your Car class does not use MockCarRepository but has it's own empty list instead (CarList).

You should either populate the list in the Car or use the mock repository there.


推荐阅读