我得到了一个包含3个一对多关系的表(一对多对多关系以及与额外数据的第三对多关系),但我想从多对多关系的一方支撑一些关系。我不希望它与多对多关系的另一方联系在一起,所以我想把它变成可空的但我(没有惊喜)不能这样做,因为它是一个主键为了它。但是,有多种解决方法可以为多对多关系中的一方获取null吗?
这是SQL源代码:
CREATE TABLE [dbo].[ConnectionPointRoutes] (
[ConnectionPointId] INT NOT NULL,
[RouteId] INT NOT NULL,
[SegmentId] INT NOT NULL,
[Position] INT NOT NULL,
CONSTRAINT [PK_dbo.ConnectionPointRoutes] PRIMARY KEY CLUSTERED ([ConnectionPointId] ASC, [RouteId] ASC, [SegmentId] ASC),
CONSTRAINT [FK_dbo.ConnectionPointRoutes_dbo.ConnectionPoints_ConnectionPointId] FOREIGN KEY ([ConnectionPointId]) REFERENCES [dbo].[ConnectionPoints] ([ConnectionPointId]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.ConnectionPointRoutes_dbo.Routes_RouteId] FOREIGN KEY ([RouteId]) REFERENCES [dbo].[Routes] ([RouteId]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.ConnectionPointRoutes_dbo.Segments_SegmentId] FOREIGN KEY ([SegmentId]) REFERENCES [dbo].[Segments] ([SegmentId]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_ConnectionPointId]
ON [dbo].[ConnectionPointRoutes]([ConnectionPointId] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_RouteId]
ON [dbo].[ConnectionPointRoutes]([RouteId] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_SegmentId]
ON [dbo].[ConnectionPointRoutes]([SegmentId] ASC);
这是模型,注意我让它可以为空但数据库仍然把它作为一个不可为空的项目
namespace InBuildingNavigator.Data.Models
{
public class ConnectionPointRoute
{
public int ConnectionPointId { get; set; }
public int? RouteId { get; set; }
public int? SegmentId { get; set; }
public int Position { get; set; }
public ConnectionPoint ConnectionPoint { get; set; }
public Route Route { get; set; }
public Segment Segment { get; set; }
}
}
对此问题的解决方法有任何想法吗?
答案 0 :(得分:0)
问题在这里得到解决:Optional One to many relationship
connectionpointroute modelbuilder必须是这样的:
modelBuilder.Entity<ConnectionPointRoute>()
.HasKey(c => new {c.ConnectionPointId, c.RouteId});