简体   繁体   中英

EF5 - Database First Create Many to Many Table

I have a Many to Many relationship in my DB:

CREATE TABLE [dbo].[PositionRequirements](
    [Position_ID] [int] NOT NULL,
    [Requirement_ID] [int] NOT NULL,
 CONSTRAINT [PK_PositionRequirements] PRIMARY KEY CLUSTERED 
(
    [Position_ID] ASC,
    [Requirement_ID] ASC
)

When I generate the model in EF5, I don't see a table, but rather an association with two collections of each side in their respective FK tables. So I have a collection of Positions in Requirements , and a collection of Requirements in Positions . Fair enough, I understand what is going on here.

I stumbled across this question, showing how to delete a Many-to-Many row:

How to add or remove a many-to-many relationship in Entity Framework?

The problem is though, I can't see any way to genericize this functionaility, however if there was a Table defined in the Model, I can see this would be relatively easy.

Is there a way to "trick" EF into creating the MM table, rather than the association collections?

I've seen this page along with using IDatabaseInitializer<> interface, however it doesn't seem to work - I don't see a table in the Diagram.

This would simplify a lot of things in my current project.

Hopefully this helps. In my scenario I have a list box with embedded checkboxes per item. I want to be able to add/remove checked items.

The 'dto' object below is sent from the client. It's checking the selected state for each item in the list. If anyone knows of any way to improve this any more please leave feedback.

DB Schema: [logger] m:m [logger_to_file_appender] m:m [file_appender] My junction table only has 2 fields, FKs, that act as a composite key. As you've noted the EDMX file will not contain this junction table. Below is my solution....

file_appender selectedAppender = context.file_appender.Find(dto.Id);

int[] ids = dto.Loggers.Where(x => !x.Selected).Select(x => x.Id).ToArray();
var loggers_to_delete = selectedAppender.logger.Where(x => ids.Contains(x.id));
loggers_to_delete.ToList().ForEach(x =>
{
    selectedAppender.logger.Remove(x);
});

ids = dto.Loggers.Where(x => x.Selected).Select(x => x.Id).ToArray();
var loggers_to_add = context.logger.Where(x => ids.Contains(x.id));
loggers_to_add.ToList().ForEach(x =>
{
    selectedAppender.logger.Add(x);
});

Sometimes working in the Entity Framework can be frustrating because something as basic as this, which would take me 2 minutes to accomplish in T-SQL, took me about a day to conquer :(. Hopefully this knowledge will save someone hours.

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