Reputation: 1395
TL;DR
I would like for multiple compositions to the same class using Entity Framework to be mapped in a different way, with the component having a single foreign key to the composer, or with a table in between.
Proper explanation
I am designing some code using Enterprise Architect. The UML for the interested classes looks like this:
The generated code, in C#, is
public class A
{
public int id { get; set; }
public List<B> foo { get; set; }
public List<B> bar { get; set; }
}
public class B
{
public int id { get; set; }
// fields...
}
Great! That's how I want it. However, my Entity Framework code first approach (cannot be changed, has been used for years in the project) creates some migrations that are not exactly as I would like them to be.
A is a table with only its fields (in the example, id). B is as the following:
| id | field1 | field2 | A_ID1 | A_ID2 |
Well, it works, but the problem is that in the real scenario, I have something like ten compositions to multiple classes. The same instance of B won't ever be shared between multiple classes. The result is a table like this
| id | field1 | field2 | A_ID1 | A_ID2 |
| 1 | .. | .. | 1 | null |
| 2 | .. | .. | 2 | null |
| 2 | .. | .. | null | 3 |
I.e. only one foreign key per row (and I repeat this because it's what bothers me most, there are plenty of foreign keys) is not null, all others are null.
Do you have any suggestion to improve this mapping? The tooling I am using is
Enterprise Architect <-> Entity Framework <-> EF Code First Migrations
Upvotes: 0
Views: 388
Reputation: 13784
Seems like conceptually you only have one relation from A
to B
. From each link however you need to know whether it's foo
or bar
In a logical data model I would probably model that like this:
In a database that could be implemented with a link table ABProperties
that has a foreign key to both A
and B
, and has a extra column ABType
that holds Foo
or Bar
Adding a unique constraint on the FK to B should ensure the upperbound constraint of 1, making sure you can't connect a row of B
with more than one A
As I'm not familiar with your toolset for code generation, I'm not sure if it even supports association classes.
If you toolset doesn't support association classes you could set the type as a property of the B
class.
It's not as clean as the solution with the association class, but I think it would work since a B
can only be part of one A
Upvotes: 1