views:

34

answers:

2

Hello,

In some instances, we may have PK/FK references duplicated, so entity A and entity B are in a PK/FK relationship, but 3 times. So entity A would have 3 FK collections and entity B would have 3 entity references. How does that work with the code-first template? Do you follow the naming convention of Entity Framework model/database first approaches (EntityA, EntityA1, etc.), and it knows how to hook those relationships up, or is there an extra step, or what?

Thanks.

+2  A: 

If you were to define your classes like this

public class EntityA
{
    public int EntityAId { get; set; }
    public virtual EntityB EntityB1 { get; set; }
    public virtual EntityB EntityB2 { get; set; }
    public virtual EntityB EntityB3 { get; set; }
}

public class EntityB
{
    public int EntityBId { get; set; }
    public string Name { get; set; }
}

EF Code First would create two tables (EntityAs, EntityBs). By convection the EntityAs table would have a primary key of EntityAId and three foreign keys linking to EntityB called (EntityB1_EntityBId, EntityB2_EntityBId, EntityB3_EntityBId).

You can however override this convection by adding properties for the foreign keys and adding RelatedTo tags on the navigation properties.

For example:

public class EntityA
{
    public int EntityAId { get; set; }
    public int MySpecialFkName { get; set; }
    [RelatedTo(ForeignKey = "MySpecialFkName")]
    public EntityB EntityB1 { get; set; }
}

If you didn't want the RelatedTo meta data in your POCO class, you could instead define the relationship in the OnModelCreating method.

modelBuilder.Entity<EntityA>().HasRequired(p => p.EntityB1)
            .HasConstraint((fk, pk) => fk.MySpecialFkName == pk.EntityBId);
ckal
A: 

For what its worth, this also helped solve the issue in the reverse direction: http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/38edb82c-c3b1-4612-991f-2155fcbb991b

Brian