0

Preface: I have no control over the database schema. In this question I've renamed the fields/tables to make it easier to understand. I've included the [Key] and [ForeignKey()] annotation in my example, but I'm really trying to define it in fluent api.

public partial class Person
{
    [Key]
    public int p_id{ get; set; }
    [Key]
    public int p_id2{ get; set; }

    public int? p_document_id { get; set; }

    [ForeignKey("p_document_id")
    public virtual ICollection<Document> Documents { get; set; }
}

public partial class Document
{
    [Key]
    public int d_id { get; set; }
    [Key]
    public int d_id2 { get; set; }

    //implied?
    //public virtual Person Person {get; set;}
}

A person may have 0 or many Documents. A document must belong to one person. Each table has a composite key.

Here's an example of what the database could look like:

p_id     p_id2   p_document_id
1        a       NULL
1        b       NULL
2        a       555
2        b       666

d_id     d_id2   
555      x
555      y
666      x

In this example person 1 has no documents, but person 2 has 3 documents. Person.p_document_id = Document.d_id , d_id2 is only there to provide a composite unique id.

Is there anyway to set up this relationship in fluent api with what I've got to work with, I'm unable to add any new columns.

  • Since a person has a `document id`, it can't have an associated collection of documents. It'd make sense to put a `person id` in the `documents` table. Other than that I suggest reading the [manual](https://msdn.microsoft.com/en-us/data/jj591617.aspx). – h.alex Jun 15 '15 at 17:49
  • Ah I forgot to clarify further, p_document_id = d_id. d_id2 is only there to have a composite uniqueid. Although I'd want both 555/x,555/y to show up when I reference person 2/a's documents. – cylonshaditright Jun 15 '15 at 17:51
  • That doesn't look right on a couple of levels. document_id and collection in person, etc. If you have an existing database, I would recommend letting EF generate the classes and fluent api for you and then tweaking that code. https://msdn.microsoft.com/en-us/data/jj200620.aspx – Steve Greene Jun 15 '15 at 18:23
  • Having the collection in person is my goal, but all I have connecting the two is the document_id. I think I may end up having to join the two in linq. – cylonshaditright Jun 15 '15 at 18:31

0 Answers0