开发者

LINQ to Entities - assigning many to many relations

I need to write something like the following, which creates some Table1 <==> Table2 relations.

table1.Table2 = context.Table2.Where(t => t.ID.In(arrayOfIDs))

Table1 and Table2 have a many to many relationship, eg they h开发者_如何转开发ave a joining table in the database. How do I do it?

edit:

A fuller example:

internal void UpdateMedia(int mediaID, int[] catagoryIDs)
{
    using (Data.EFEntities context = new Data.EFEntities())
    {
        Data.Media media = context.Media.Single(m => m.MediaID == mediaID);

        media.Category = context.Category.Where(cat => cat.CategoryID.In(catagoryIDs));

        context.SaveChanges();
    }
}

This doesn't work, but should show what I am trying to achieve. (Entity Framework 4 btw)


Maybe something like this would work:

internal void UpdateMedia(int mediaID, int[] catagoryIDs)
{
    using (Data.EFEntities context = new Data.EFEntities())
    {
        Data.Media media = context.Media.Single(m => m.MediaID == mediaID);

        foreach(var category in context.Category.Where(cat => catagoryIDs.Contains(cat.CategoryID))
        {
            media.Categories.Add(category);                
        }

        context.SaveChanges();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜