EntityFramework:数据库设计m对1关系

EntityFramework: Database design m to 1 relationship

我喜欢在数据库中存储一个集合,其中包含一组可用的"Wheels"。一辆汽车 class 参考这些轮子。

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; }
}

如果我使用 entity framework,外键将存储在 Wheels-DataBase Table 中。这不是我想要的结果,因为我有多辆汽车,并且对于每辆汽车,将在 Wheels 中创建一个具有相同内容的新条目。 (浪费存储空间space)

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

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

所以我尝试了另一种解决方案,强制为 Car-Wheel 关系创建第三个 table。因此 ID 将存储在相应的 Car_Wheel table.

我在 Wheel-class 中添加了一个 属性 用于聚焦多对多关系。

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

Wish 创建 table 方案:

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

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

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

???所以这看起来不错,但我正在寻找不需要更换车轮的解决方案-class。???

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

您描述的是 m to n(多对多)问题,而不是 m to 1。因此,您必须使用路口 table.

您描述的解决方案看起来不错。

如果你想去掉 Wheel 中的导航 属性 你可以看看这个 post: Map Many to Many relationship without navigation property