如果您的桥接表没有任何有趣的列(除了MessageId
and之外ContractId
),那么它在您的模型中就没有用了。
而且您只想Message.Contracts
导航属性(您不需要Contract.Messages
)。
使用 Model First 方法,只需将 2 个实体拖放到设计器并配置多对多关联:
由于您不需要Contract.Messages
,只需单击导航属性并将其删除。
当您从模型创建数据库模式时,Entity Framework 将为您生成桥表:
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
-- Creating table 'Messages'
CREATE TABLE [dbo].[Messages] (
[Id] int IDENTITY(1,1) NOT NULL,
[Value] nvarchar(max) NOT NULL
);
GO
-- Creating table 'Contracts'
CREATE TABLE [dbo].[Contracts] (
[Id] int IDENTITY(1,1) NOT NULL,
[Value] nvarchar(max) NOT NULL
);
GO
-- Creating table 'MessageContract'
CREATE TABLE [dbo].[MessageContract] (
[Messages_Id] int NOT NULL,
[Contracts_Id] int NOT NULL
);
GO
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
-- Creating primary key on [Id] in table 'Messages'
ALTER TABLE [dbo].[Messages]
ADD CONSTRAINT [PK_Messages]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
-- Creating primary key on [Id] in table 'Contracts'
ALTER TABLE [dbo].[Contracts]
ADD CONSTRAINT [PK_Contracts]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
-- Creating primary key on [Messages_Id], [Contracts_Id] in table 'MessageContract'
ALTER TABLE [dbo].[MessageContract]
ADD CONSTRAINT [PK_MessageContract]
PRIMARY KEY NONCLUSTERED ([Messages_Id], [Contracts_Id] ASC);
GO
-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------
-- Creating foreign key on [Messages_Id] in table 'MessageContract'
ALTER TABLE [dbo].[MessageContract]
ADD CONSTRAINT [FK_MessageContract_Message]
FOREIGN KEY ([Messages_Id])
REFERENCES [dbo].[Messages]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating foreign key on [Contracts_Id] in table 'MessageContract'
ALTER TABLE [dbo].[MessageContract]
ADD CONSTRAINT [FK_MessageContract_Contract]
FOREIGN KEY ([Contracts_Id])
REFERENCES [dbo].[Contracts]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Creating non-clustered index for FOREIGN KEY 'FK_MessageContract_Contract'
CREATE INDEX [IX_FK_MessageContract_Contract]
ON [dbo].[MessageContract]
([Contracts_Id]);
GO