I was looking at using the EF for a project I will be starting in the coming weeks.
I have three tables in a previously created database. (please see image attached)
When a CompanyNotice record is created at least one Location must be added (from the Locations table) into the CompanyNoticeLocations table.
e.g.
**CompanyNotice**
ID CompanyID Date Heading Text .....
2 9 2011-11-21 10:17:29.573 Lorem Ipsum 1 1 1
**CompanyNoticeLocations**
CompanyNoticeLocationsID CompanyNoticeID LocationID
1 2 4
2 2 5
3 2 1
Main question:
Can anyone please tell me if I can use the EF to create an Entity called: CompanyNoticesWithLocations that just returns:
- Heading
- Text
- List of LocationNames
Sub Question: I have tried doing this with LINQ without the multiple table to Entity mapping and I couldn’t get that to work either:
using (var context = new ALEntities())
{
var query = from c in context.CompanyNotices.Include("Locations")
select new
{
c.CompanyNoticeHeading,
c.CompanyNoticeText,
(from l in c.CompanyNoticesLocations select l.Location.LocationName)
};
ASPxGridView1.DataSource = query;
ASPxGridView1.DataBind();
}
However I get an error:
Invalid anonymous type member declarator. Anonymous type members must
be declared with a member assignment, simple name or member access.
Your CompanyNoticesLocation table doesn’t need to exist as a separate entity in the model. This should be represented as a many to many Association between CompanyNotice and Location. As long as the Association is setup correctly EF will map this to your underlying join table which you’ll be able to see in the Mapping window.
Here’s an example of a many to many mapping from one of my own models showing the Association mapping to the underlying join table called CandidateAnswer: