Pauli
Pauli

Reputation: 363

C# - Referencing objects in MVC data model

I'm building a piece of software using the MVC pattern in C#. The software has a complex data model with a number of classes and creates on runtime lot's of objects of those model classes (controlled by the user). However, the objects of one class (ParkingGarage) reference to the objects of the other class (Car) - so the ParkingGarage objects store references to all Car objects (in an Array), which are currently parked in the specific garage.

Class Car

- Property (String) Model
- Property (String) Color
- Property (String) LicensePlate

Class ParkingGarage

- Property (String) Name
- Property (String) LocationAddress
- Property (Array) ParkedCars

When now storing the Car objects in the Array of the ParkingGarage objects, can I just have an Array full of Car objects or should I store only some kind of an identifier (maybe a property uniqueIdentifier of the Car class)?

My current assumption is: If I add Car objects to the Array ParkedCars of a ParkingGarage object, the array holds only references to the car object, right? Do I get any issues with that?

Upvotes: 1

Views: 2625

Answers (1)

chomba
chomba

Reputation: 1441

Leave memory management issues to the runtime and use the generic List type List<> instead of an array to hold your data. List<T> represents a growable list of objects and provides methods such as Add and Remove which in fact manipulate and array of T under the covers to produce the desired result.

Here's some code you can use as a guideline.

public class Car
{
    public int Id { get; set;}
    public string Model { get; set; }
    public string Color { get; set; }
    public string LicensePlate { get; set; }

}

public class ParkingGarage
{
    private List<Car> parkedCars;

    public int Id { get; set; }
    public string Name { get; set; }
    public string LocationAddress { get; set; }

    public List<Car> ParkedCars
    {
        get { return parkedCars; }
    }

    public ParkingGarage()
    {
        parkedCars = new List<Car>();
    }

    public void AddCar(Car car)
    {
        // perform validation
        parkedCars.Add(car);
    }
}

To retrieve Cars from your Database you can use the repository pattern:

public class CarRepository
{
    public List<Car> FindAll()
    {
        // Code to retrieve all cars 
        List<Car> cars = new List<Car>();
        // Retrieve All rows from Cars Table and populate the List
        return cars;           
    }

    public List<Car> FindAllWith(string carModel)
    {
        // Code to retrieve all cars with a particular model
    }

    public List<Car> FindAllWith(int parkingGarageId)
    {
        // Code to retrieve all cars from a particular parking garage
    }

    public void Save(Car car)
    {
       // Code to save car to the database
    }

}

Again, Do not worry about memory management, you better focus on creating a good model for your project.

Upvotes: 1

Related Questions