megaspazz
megaspazz

Reputation: 9

One-sided many-to-many relationship in EF6

Here's an example of what I mean:

We have a Color class containing some information about some color:

public class Color
{
    public int ID { get; set; }

    public int R { get; set; }
    public int G { get; set; }
    public int B { get; set; }
    // ... more properties
}

And a Palette class, which is a collection of colors (i.e. has-many Colors).

public class Palette
{
    public int ID { get; set; }

    public string Name { get; set; }
    // ... more properties

    public virtual ICollection<Color> Colors { get; set; }
}

So a Palette has a lot of different Colors, and a Color can be part of multiple Palettes, but a Color doesn't have to know what Palettes it belongs to.

What would be the best way to model this relationship? I know you can create a join table, and then create the Colors property to get the collection of Colors from the join table. Is it possible to model this one-sided relationship without the join table, so I don't have to create another model and have another table in the database?

And I also believe that this causes a column called Palette_PaletteID or something similar to be created in the Color table. Since this column is never used, is there some way to prevent it from being created?

Upvotes: 0

Views: 205

Answers (2)

Michael Fox
Michael Fox

Reputation: 611

I think that you're looking at this the wrong way. When using an ORM like Entity Framework you shouldn't be worrying necessarily about the Tables that it produces unless you specifically run into performance issues caused by a database problem.

One of two things is going to occur: EF is going to create a lookup table that contains a list of Color IDs associated to each Palette ID OR it's going to create multiple entries for each color that have a Pallet ID for each palette it belongs to. Frankly, I think either of these are just fine and you should assume so as well until you run into a specific problem caused by this.

Upvotes: 2

CameronP
CameronP

Reputation: 305

This is how EF works, building relationships and referential integrity in the database.

However, if you want your Color to not know about Palettes, you can simply create another more focused data access layer that contains specialized entities and DbContext that contains the relationships how you want them. In domain driven design terms, this is called a bounded context. See http://msdn.microsoft.com/en-us/magazine/jj883952.aspx. So, you'll have your primary DbContext that will create all possible relationships and another one that is lightweight and focused for your specific needs.

Upvotes: 2

Related Questions