开发者

LINQ query, a connection table issue

I want to write a query that presents for every event (tbl_events) all objects (tbl_objects) related to it (relation type — M:N).

I have a problem with tables that are connection tables (association class) that holds only foreign keys of the 2 tables that connects.

For instance, tbl_events is connected with a connection table named tbl_object_has_tbl_events to tbl_objects.

Here is a structure of connected tables:

tbl events has: eventID, eventName

tbl_object has: objectID, objectName

tbl_object_has_tbl_events: eventID, objectID

Here is what I tried to write:

IList dataList = (from dEvent in App.glidusContext.tbl_events.
                    join dObject in App.glidusContext.tbl_objects
                    on dEvent.tbl_objects equals dObject.objectID
                    select new { dEvent.eventName, dObject.objectName}).ToList();

I can't reach the connection table tbl_object_has_tbl_events

How I can implement such query, when I have an M:N relationship?

UPDATE Generation of Many-to-many relationship:

-- -----------------------------------------------------
-- Table tbl_events
-- -----------------------------------------------------
CREATE TABLE tbl_events (
    eventID INT NOT NULL IDENTITY,
    eventName NVARCHAR(100) NOT NULL,
    PRIMARY KEY (eventID));

-- -----------------------------------------------------
-- Table tbl_objects
-- -----------------------------------------------------
CREATE TABLE tbl_objects (
    objectID INT NOT NULL IDENTITY,
    objectName NVARCHAR(100) NOT NULL,
    PRIMARY KEY (objectID));

-- -----------------------------------------------------
-- Table tbl_objects_has_tbl_events
-- -----------------------------------------------------
CREATE TABLE tbl_objects_has_tbl_events (
    objectID INT NOT NULL,
    eventID INT NOT NULL,
    PRIMARY KEY (objectID, eventID),
    CONSTRAINT fk_tbl_objects_has_tbl_events_tbl_objects
        FOREIGN KEY (objectID)
           开发者_JAVA技巧 REFERENCES tbl_objects (objectID)
                ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT fk_tbl_objects_has_tbl_events_tbl_events
        FOREIGN KEY (eventID)
            REFERENCES tbl_events (eventID)
                ON DELETE CASCADE ON UPDATE CASCADE);


The entity data model doesn't show tables that only contain FK's. So in your case the Events entity will have a navigation property Objects and your Object entity will have a navigation property Events.

So to get your information you could write a query like this:

IList dataList = (from dEvent in App.glidusContext.tbl_events
                  from dObject in dEvent.Objects
                    select new { dEvent.eventName, dObject.objectName}).ToList();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜