locked
How to create 1-to-1 relationship in EF code first using a map/link table with fluent configuration RRS feed

  • Question

  • I have a situation where I would like to create a 1-to-1 relationship in Entity Framework (4.2) using code first fluent configuration API, the twist is that I need to use a link/map table to do it.

    Here is a diagram of my table layout.

     

     

    This is what I am after ...

    HasOptional(x => x.FieldPerson)
        .WithOptionalPrincipal()
        .Map(map =>
                 {
                     map.ToTable("user_account__field_person");
                     map.MapLeftKey("user_account_id");
                     map.MapRightKey("field_person_id");
                 });
    

     

    ... but there doesn't seem to be a way to do it.

    The alternative is to create my 3 entities and manage them myself using joins where appropriate.

    Is this even possible or is it a scenario that EF fluent API doesn't handle?

     

     

    Thursday, January 19, 2012 5:12 PM

Answers

  • What I did was create the database matching yours then used EF Power Tools to reverse engineer code first the db and it gave me this:

    this.HasMany(t => t.UserAccounts)
    	.WithMany(t => t.FieldPersons)
    	.Map(m =>
            {
                m.ToTable("UserAccountFieldPerson");
                m.MapLeftKey("FieldPersonId");
                m.MapRightKey("UserAccountId");
            });
    

    Sorry, I just can't do underscores ;)

    Try the tools. Ace they are.

    Richard

     

    • Marked as answer by Antony Scott Monday, January 23, 2012 3:56 PM
    Thursday, January 19, 2012 10:18 PM

All replies

  • What I did was create the database matching yours then used EF Power Tools to reverse engineer code first the db and it gave me this:

    this.HasMany(t => t.UserAccounts)
    	.WithMany(t => t.FieldPersons)
    	.Map(m =>
            {
                m.ToTable("UserAccountFieldPerson");
                m.MapLeftKey("FieldPersonId");
                m.MapRightKey("UserAccountId");
            });
    

    Sorry, I just can't do underscores ;)

    Try the tools. Ace they are.

    Richard

     

    • Marked as answer by Antony Scott Monday, January 23, 2012 3:56 PM
    Thursday, January 19, 2012 10:18 PM
  • Thanks. I realised that there is nothing in my database schema to prevent a many-to-many relationship. However, if I did want that behaviour then I would need to add unique constraints on the fields in the link table.
    Monday, January 23, 2012 3:58 PM