Having difficulty seeing how to work with many-to-many relationships in MVC2 / EF4

I wrote about this several times, but it’s still hard for me to understand how to work with many-to-many relationships in MVC2 with EF4, especially when it comes to Create and Edit features. I believe that part of my problem is that I decided to create the database tables so that the pivot tables are not visible in the model itself.

My tables 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)

, GamePlatform, , , . , , , , , .

, HTTP-. , .

, . , , , .

, , , .

+3
1

, , Game , , / .

value PlatformID , , "platformids". , Html.CheckBox() HtmlHelper 'value', htmlAttributes. MVC- "platformid" IEnumerable, .

, :

// 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);
}

. BuildOrExpression() - SQL- SELECT * FROM TABLE WHERE ID IN(1,2,3,4,5,...).

+1

Source: https://habr.com/ru/post/1774171/


All Articles