0

I like to store a collection in database, which contains a set of available "Wheels". A car class reference to these wheels.

public class Car
{
    private ICollection<Wheel> _wheels;

    public ICollection<Wheel> Wheels
    {
        get { return _wheels; }
        set { _wheels = value; }
    }


}

public class Wheel
{
    public enum position
    {
        FrontRight,
        FrontLeft,
        BackRight,
        BackLeft,
    }

    [Key]
    public int ID { get; set; }
}

If I use the entity framework the foreignkey will be stored in the Wheels-DataBase Table. Which is not the wished result, because I have multiple Cars and foreach car a new entry in Wheels will be created with the same content. (Waste of storage space)

Wheels
-------
<PK>ID:Integer
<FK>Car_ID:Integer

Cars
-----
<PK>ID:Integer

So I tried another solution by forcing the creation of a third table for the Car-Wheel relationship. So the ID's will be stored in the corresponding Car_Wheel table.

I added a property to the Wheel-class for focusing a many-many-relationship.

public virtual ICollection<MonitoringTask> RelatedCars { get; set; }

Wish creates the table scheme:

Wheels
-------
<PK>ID:Integer

Cars
-----
<PK>ID:Integer

Car_Wheel
-------
<PK><FK> ID_Car:Integer
<PK><FK> ID_Wheel:Integer

???So this looks good, but I'm searching for a solution which does not require the change of the Wheel-class.???

Kinimod
  • 166
  • 1
  • 15
  • I guess `MonitoringTask` in the example should be `Car`. And you are talking about `many-to-many` relationship. Are you asking how to setup many-to-many relationship without navigation property at the `Wheel` side? – Ivan Stoev Jun 20 '17 at 09:34

1 Answers1

1

"because I have multiple Cars and foreach car a new entry in Wheels will be created with the same content."

you are describing an m to n (many to many) Problem, not an m to 1 . Therefore you have to go with a junction table.

The solution you described looks fine.

If you want to get rid of the navigation property in Wheel you can take a look at this post: Map Many to Many relationship without navigation property

Fabiano
  • 5,124
  • 6
  • 42
  • 69