EF – manage to-many associations

This post teaches you to manage to-many associations (i.e. relationships) between entities.

.

As an example, we’ll use the Document and Category entities that were defined for your programming assignment’s blogging module.

.

The purpose of “categories”

You can create a “category” to help you organize your blog posts. A category can be a word or a phrase.

The suggested Category entity appears below. It is associated (related) with the Document entity, with a two-way to-many association. That is, a Category can be used by many Documents, and a Document can use many Categories.

.

Display and create categories

Create a standard web form (or a user control) to enable you to create new categories.

To display your categories, you can use any data display control, including list controls.

.

Setting the Document – Category association

Get a reference to a Document object. You may fetch one from the store, or create a new one.

Get a reference to a Category object. As above, you may fetch or create.

If you want to add the Category to the Document’s “Categories” collection, use the collection’s “Add()” method. For example:

doc.Categories.Add(cat);

You do not have to add the Document to the Category’s “Documents” collection. Setting the association above will enable you to use it both ways.

If you want to remove the Category from the Document’s “Categories” collection, use the collection’s “Remove()” method. For example:

doc.Categories.Remove(cat);

.


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: