Reputation: 6042
I've written about this a few times, but am still having difficulty seeing how to work with many-to-many relationships in MVC2 with EF4, specifically when it comes to Create and Edit functionality. I think part of my problem is that I decided to create my database tables in such a way that the pivot tables aren't visible in the model itself.
My tables, once again:
Games:
int GameID (primary key, auto-incr)
string GameTitle
string ReviewTitle
int Score
int ReviewContentID (foreign key from Content - News, Articles, and Game reviews all have similar content requirements)
int GenreID (foreign key from Genres)
Platforms:
int PlatformID (primary key, auto-incr)
string Name
GamePlatform (not visible in model):
int GameID (foreign key from Games)
int PlatformID (foreign key from Platforms)
When I create a new review, I really just want to add entries to the GamePlatform pivot table, as I'm just trying to link the game I reviewed to the already existing platforms. Dealing with it in an OOP level is confusing me as I keep thinking I'm adding to Platforms, when all I really want to do is link Games' id to various Platform ids.
So, I don't want to create a new Platform from the incoming HTTP-Post data. I just want to be able to take the form data and create a new Game, new review Content, and link the new Game to existing Platforms based on selected checkboxes.
I understand how to perform the first two tasks. It's the linking I can't seem to grasp.
Apologies for continuing to harp on this, but it's really the one thing holding me back from making significant progress.
Upvotes: 3
Views: 261
Reputation: 24606
Assuming you have correctly mapped this in entity framework and your Game object has a Platforms collection then assigning existing Platforms to a Game should be as simple as passing the IDs of those platforms to your Game add/edit action.
In your form you can use a series of checkboxes with a value attribute of PlatformID and a single common name, 'platformids' for example. Note, the Html.CheckBox()
HtmlHelper doesn't have a parameter for 'value', so you'll have to specify it by way of the htmlAttributes object. MVC's default model binder will automatically group your collection of 'platformid' values in the form into a single typed IEnumerable by adding a matching parameter to the receiving action.
Here's some code to get you started:
// games controller
public action AddGame(Game newGame, int[] platformIds) {
Platforms[] platforms;
if(platFormIds != null && platformIds.Any()) {
platforms = ObjectContext.Platforms.Where(ExpressionExtensions.BuildOrExpression<Platform, int>(p => p.PlatformID, platformIds)).ToList();
}
if(ModelState.IsValid()) {
game.Platforms.AddRange(platforms);
ObjectContext.AddToGames(game);
ObjectContext.SaveChanges();
}
}
// helper class
public static Expression<Func<TElement, bool>> BuildOrExpression<TElement, TValue>(Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values) {
if (valueSelector == null) throw new ArgumentNullException("valueSelector");
if (values == null) throw new ArgumentNullException("values");
ParameterExpression p = valueSelector.Parameters.Single();
if (!values.Any())
return e => false;
IEnumerable<Expression> equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate(Expression.Or);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
Note: The BuildOrExpression()
above is just a nice way to create the SQL equivalent of SELECT * FROM TABLE WHERE ID IN(1,2,3,4,5,...)
.
Upvotes: 1