多个表的一对多关系
本文关键字:一对多 关系 | 更新日期: 2023-09-27 18:12:17
我对EF
的数据库设计很陌生,并试图理解如何正确地将我的实体模型转换为DB表。
我有以下两个类:
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
对象的列表
我的计划是通过以下方式实现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; }
}
这样,我的每个例外实体将同时拥有Test和Measurement表的外键,然而在每个例外实体中,要么是Test,要么是Measurement,因为一个例外不能同时来自Test或Measurement。
这工作,但我想知道如果这是正确的方式去,或者如果有一个更好的做法。
谢谢
Virtual for EF标识连接
与"虚拟集合"的许多和只有一个
的"virtual object"测试有许多测量值和Measurement有一个Test
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[ForeignKey("TestRefId")]例:
[ForeignKey("TestRefId")]
public virtual Test Test { get; set; }
表转到TestRefId以标识Test
Sorry for my english