【问题标题】:One to Many relationship for multiple tables多个表的一对多关系
【发布时间】:2015-09-10 18:55:41
【问题描述】:

我对@9​​87654321@ 的数据库设计非常陌生,并试图了解如何正确地将我的实体模型转换为数据库表。

我有以下两个类:

public class Test 
{
    public int ID { get; set; }
    // ... more data
    ICollection<Exception> Exceptions { get;set; }
}

public class Measurement 
{
    public int ID { get; set; }
    // ... more data
    ICollection<Exception> Exceptions { get;set; }
}

所以我的两个类 Test 和 Measurement 都将包含 Exception 对象的列表

我的计划是通过以下方式实现异常:

public class Exception
{
    public int ID { get; set; }
    // ... more data

    /// <summary>
    /// Reference to Test to create One-To-Many relationship
    /// </summary>
    public Test Test{ get; set; }

    /// <summary>
    /// Foreign key of Test table
    /// </summary>
    public int TestID { get; set; }

    /// <summary>
    /// Reference to Measurement to create One-To-Many relationship
    /// </summary>
    public Measurement Measurement { get; set; }

    /// <summary>
    /// Foreign key of Measurement table
    /// </summary>
    public int MeasurementID { get; set; }
}

这样,我的每个异常实体都将具有测试和测量表的外键,但是在每个异常实体中都将显示测试或测量,因为一个异常不能同时来自测试或测量。

这行得通,但我想知道这是否是正确的方法,或者是否有更好的做法。

谢谢

【问题讨论】:

  • 您是否要求进行代码审查?
  • 不是真正的代码审查,而是更多的策略。
  • 可能想要使测试和测量属性虚拟化。
  • 那会做什么?谢谢

标签: c# .net database entity-framework one-to-many


【解决方案1】:

虚拟 EF 识别连接

为许多人提供“虚拟收藏” 和 只有一个“虚拟对象”

测试有很多测量 和测量有一个测试

public class Test
{
    public int Id { get; set; }
    public string Testname { get; set; }
    public virtual ICollection<Measurement> Measurements { get; set; }
}
public class Measurement
{
    public int Id { get; set; }
    public int FullMeasurement { get; set; }
    public virtual Test Test { get; set; }
}

你有一个 DataAnnotation [外键(“TestRefId”)] 例如:

[ForeignKey("TestRefId")]
public virtual Test Test { get; set; }

该表转到 TestRefId 以识别测试

对不起我的英语

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多