简体   繁体   中英

EF4: Define multiple foreign keys

So I have a table people which is like this

Id    Name
1     John
2     Mike
3     Sophie

And I have a table Calls

Id    IdReceptor    IdRequired
1     1             2
2     1             1
3     2             3
4     3             1

Basically a person answers a telephone call, that person is the receptor, the one on the phones requires to talk with another person, it can be the same person who answered, or other, so we have this table design, IdReceptor and IdRequired both are foreign keys to people

How can I model this using EF4 Code First?

For example like so:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Call
{
    public int Id { get; set; }

    [ForeignKey("Receptor")]
    public int IdReceptor { get; set; }
    [ForeignKey("Required")]
    public int IdRequired { get; set; }

    public Person Receptor { get; set; }
    public Person Required { get; set; }
}

You can introduce collections in Person if you want and add additional mapping with annotations or Fluent API or you can make the Person navigation properties virtual if you want lazy loading. But the code above is a simple solution. EF will detect two one-to-many relationships by convention.

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