简体   繁体   中英

One to Many relationship for multiple tables

I am pretty new to database design with EF and trying to understand how to properly translate my Entity Models into DB tables.

I have the following two classes:

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

So my both classes Test and Measurement will contain list of the Exception objects

My plan was to implement exception in the following way:

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

This way, my each Exception entity will have foreign keys to both Test and Measurement tables, however in each Exception entity either Test or Measurement will be presented since one exception cannot be from both Test or Measurement.

This works, but I was wondering if that's the right way to go or if there is a better practice.

Thanks

Virtual for EF identify the connection

with "virtual Icollection" for Many and with only "virtual object" for one

Test have many Measurements and Measurement has a 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; }
}

and you have a DataAnotation [ForeignKey("TestRefId")] for exemple:

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

the table goes to TestRefId for identify Test

Sorry for my english

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM