简体   繁体   中英

How can I access data from my junction table?

I have created a junction table between two of my tables to create a many to many relationship between them.I am able to save data to them, but can't access that data again. This is written in MVC ASP.NET by the way.

My first table:

CREATE TABLE [dbo].[UserInfo] (
[Id]        INT             IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (50)   NULL,
[LastName]  NVARCHAR (50)   NULL,
[Email]     NVARCHAR (256)  NOT NULL,
[Image]     VARBINARY (MAX) NULL,
[Approved]  BIT             NOT NULL,
[Color]     NVARCHAR (10)   NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

My second table:

CREATE TABLE [dbo].[Events] (
[Id]        NVARCHAR (128) NOT NULL,
[Name]      NVARCHAR (100) NOT NULL,
[StartDate] DATETIME       NULL,
[EndDate]   DATETIME       NULL,
[Approved]  BIT            NOT NULL,
[room_id]   INT            NULL,
[color]     NVARCHAR (10)  NOT NULL,
[Owner]     INT            NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Events_Rooms] FOREIGN KEY ([room_id]) REFERENCES [dbo].[Rooms] ([_key])
);

My junction table:

CREATE TABLE [dbo].[UserToEvent] (
[UserId]  INT            NOT NULL,
[EventId] NVARCHAR (128) NOT NULL,
CONSTRAINT [UserId_EventId_pk] PRIMARY KEY CLUSTERED ([UserId] ASC, [EventId] ASC),
CONSTRAINT [FK_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfo] ([Id]),
CONSTRAINT [FK_Event] FOREIGN KEY ([EventId]) REFERENCES [dbo].[Events] ([Id])
);

Code to add new relationship:

Event e = await db.Events.FindAsync(id);
string email = User.Identity.Name;
UserInfo user = db.UserInfoes.Where(x => x.Email == email).First();
user.Events.Add(e);
e.UserInfoes.Add(user);
db.Entry(user).State = EntityState.Modified;
db.Entry(e).State = EntityState.Modified;
await db.SaveChangesAsync();

Code to access relationship:

UserInfo user = await db.UserInfoes.FindAsync(id);
List<Events> events = user.Events;

I would expect events to be filled with all events associated with user, but it never has any events.

I have found a work-around which is sufficient to my needs. I added another attribute to my junction table, which then allowed me to access it within my controllers (Since there weren't only two primary keys). From here I was able to gather the data from it just like any other table. Not sure why the above method does not work however. I have used that method before without a hitch. If anyone has an answer, I would love to hear it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM