Entity frame work: many to many relationship tables

I have a news entity and I get the news based on their NewsID. Now I defined a new entity , a Group and I want to get the news based on their Group ID. I defined a Group news Table Aslo to relate this to table together.

in news model I have :

public virtual ICollection<GroupNews> RelatedGroupID { get; set; }

So I Assumed that I defined the GroupNews table values and I can use it in NewsService.

Now lets look at NewsService :

    Expression<Func<News, bool>> constraint = null;

    if (user_id > 0 && project_id > 0)
    {
        constraint = e => (e.CreatorID == user_id && e.RelatedProjectTags.Any(p => p.ProjectID == project_id));
    }
    else if (user_id > 0)
    {
        constraint = e => (e.CreatorID == user_id);
    }
    else if (project_id > 0)
    {
        constraint = e => (e.RelatedProjectTags.Any(p => p.ProjectID == project_id));
    }

    else
    {
        constraint = null;
    }

    IEnumerable<News> result_list = null;

    if (constraint != null)
    {
        result_list = newsRepository.GetMany(constraint).OrderByDescending(e => e.CreatedOn).Skip(offset);
    }
    else
    {
        result_list = newsRepository.GetAll().OrderByDescending(e => e.CreatedOn).Skip(offset);
    }

    if (count > 0)
    {
        result_list = result_list.Take(count);
    }

    return result_list.ToList<News>();
}

}

I add this line to it in order to define a constraint based on GroupID.

    else if (groupId > 0)
    {
        constraint = e => (e.RelatedGroupID.Any(n => n.GroupID == groupId));
    }

it seems wrong and gives me this error :

{"Invalid object name 'dbo.GroupNewsNews'."}

Answers


1.You does not need GroupNewsID in GroupNews table. You need to drop this column and create complex key by GroupID and NewsID. In the News entity you need to define property:

    public virtual ICollection<Group> Groups 
    { 
        get; 
        set; 
    }

In the default constructor for this entity you need to initialize property(need for lazy load):

Groups = new List<Group>();

Similar changes for Group entity.

2.In the GroupMap.cs you need to define

this.HasMany(t => t.News)
    .WithMany(t => t.Groups)
    .Map(m =>
        {
            m.ToTable("GroupNews");
            m.MapLeftKey("GroupID");
            m.MapRightKey("NewsID");
        });

3.Write tests for NewsRepository and GroupRepository.


Need Your Help

Magento: connection to other systems via xml, soap, etc (import / syncing)

magento soap csv import magento-1.7

What possibilities exist to let our magento installation connect to another system, to import and sync products? This doesn't necessarily have to be "live", or up-to-date all the time. A daily/weekly