【问题标题】:EntityFramework: Database design m to 1 relationshipEntityFramework:数据库设计 m 对 1 关系
【发布时间】:2017-06-20 09:24:26
【问题描述】:

我喜欢在数据库中存储一个集合,其中包含一组可用的“轮子”。对这些轮子的汽车类引用。

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

如果我使用实体框架,外键将存储在 Wheels-DataBase 表中。这不是希望的结果,因为我有多个 Cars 并且 foreach car 将在 Wheels 中创建一个具有相同内容的新条目。 (浪费存储空间)

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

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

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

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

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

Wish 创建表格方案:

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

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

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

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

【问题讨论】:

  • 我猜例子中的MonitoringTask应该是Car。你在谈论many-to-many 关系。您是否在问如何在Wheel 端设置没有导航属性的多对多关系?

标签: c# entity-framework many-to-many one-to-many


【解决方案1】:

“因为我有多个 Cars 并且 foreach car 在 Wheels 中有一个新条目 将使用相同的内容创建。”

您描述的是m to n(多对多)问题,而不是m to 1。因此,您必须使用连接表。

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

如果你想摆脱Wheel 中的导航属性,可以看看这篇文章:Map Many to Many relationship without navigation property

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2017-09-22
    • 2012-09-30
    相关资源
    最近更新 更多