Asaf
Asaf

Reputation: 2035

Many-to-Many relationship in WPF with EF and SQLite

I'm following this tutorial in order to implement a local database (using SQLite) for my WPF application.

Everything works as it should, although I have a logical problem I don't know how to solve using this approach. I'll simplify it below.

Database-wise, I have 2 tables (A,B) which share a many-to-many relationship, and thus require a JOIN table as well (ABJoin).

In my actual code however, I'd like to use only 2 models: A and B, which each having a list of the other type. Like this:

public class A {
    // ...fields
    List<B> bList;
}

public class B {
    // ...fields
    List<A> aList;
}

How can it be implemented in EF+SQLite?

Searching online, I have found some solutions, but nothing that applies to SQLite, so I was not sure how they'd work.

Upvotes: 2

Views: 1765

Answers (4)

nicolas2008
nicolas2008

Reputation: 1052

Entity Framework doesn't have automatic many-to-many mapping. Instead of this, you can map A and B to intermediate table as one-to-many.

If you are not obliged to use only EF, I suggest to try NHibernate ORM instead. It has convenient many-to-many mapping and generally more powerful.

Upvotes: 0

Martin
Martin

Reputation: 5623

Are you sure that it is a good idea not to have a third entity?

Lets say your two entities were DepartmentStore and Product, a typical example for an n:n relationship. A department store can sell many products and a product may be available in many departments stores. This results in a third entity which connects the two above, in the example above this would something like ProductAvailability. If you think about it more careful, then you might realize that the new connecting entity might have properties of its own. In my example this might be NumberOfProducts, will states the available quantity of a product in a certain department store.

In my experience, it is quite common for the connecting entity to have a real value that goes beyond just connecting two other entities.

I also took a look at you example which it about Album and Artist entities. Do you want to make a data model where an Album can be created by more than one Artist?

Upvotes: 0

Umair Farooq
Umair Farooq

Reputation: 1704

If you are using many to many join table then your each class should have a list of the join table.

It cannot work the way you are thinking.

Upvotes: 0

Related Questions