David
David

Reputation: 2571

Entity Framework 4.1 - Code First: many-to-many relationship

I want to build a relation like this ( a Zone is in the neighbourhood of x other zones )

public class Zone
{
    public string Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ZoneNeighourhood> ZoneNeighourhoods { get; set; }
}

public class ZoneNeighbourhood
{
    public virtual Zone Zone1 { get; set; }
    public virtual Zone Zone2 { get; set; }
}

Unfortunately this won't work, because the FKs generated by EF are not correct... How can i get a structure like this to work?

Example with 3 Zones: Zone 1, Zone 2, Zone 3

Zone 1 Neighours:

Zone 2, Zone 3

Zone 2 Neighbours:

Zone 1

Zone 3 Neighbours:

Zone1

Any advice?

Upvotes: 3

Views: 2936

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Your mapping is not correct. You are creating self referencing entity so you need separate collection for incoming and outgoing relations. Single collection is not enough.

public class Zone 
{
    public string Id { get; set; }
    public string Name { get; set; }
    [InverseProperty("NeighbourOf")]
    public virtual ICollection<Zone> NeighbourTo { get; set; }
    [InverseProperty("NeighbourTo")]
    public virtual ICollection<Zone> NeighbourOf { get; set; }
}

You don't need to map junction table unless you also want to add some additional properties to the relation.

If you want only single collection you must use fluent mapping:

public class Zone 
{
    public string Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Zone> Neighours { get; set; }
}

public class Context : DbContext
{
    public DbSet<Zone> Zones { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Zone>()
                    .HasMany(z => z.Neighbours)
                    .WithMany();
    }
}

Upvotes: 9

corlettk
corlettk

Reputation: 13574

Dave,

How about just:

public class Zone {
    public string Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Zone> Neighours { get; set; }
}

Or am I missing something? Do you NEED to model the neighbourhood as an external entity for some other reason? I wonder what database-schema the Entity-Framework would generate for that... I'm NOT an expert, in fact I'm a noob in this area. I don't THINK it has a problem with self-referncing tables like this... aleast nothing I've read so far indicates it. Let's try it and find out ;-)

Cheers. Keith.

Upvotes: 1

Related Questions