首先使用复合键和数据库之间的一对一或零关系

时间:2015-05-04 14:18:41

标签: c# sql sql-server entity-framework ef-model-first

我无法在两个表之间创建1到0..1的关系,其中主键是由两列组成的复合键。

表格以多对多关系导入EF,将关系更改为1到0..1或1比1会导致以下错误:

  

多重性在角色中无效,因为依赖角色   属性不是关键属性,是上限   依赖角色的多样性必须是*

主要表格:

CREATE TABLE [dbo].[MeasurementBlobs] (
    [MeasurementResultId]   INT NOT NULL,
    [ValueType]             SMALLINT NOT NULL,
    [Id]                    UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL,
    [Value]                 VARBINARY(MAX) FILESTREAM NOT NULL,
    CONSTRAINT [PKMeasurementBlobs] PRIMARY KEY CLUSTERED ([MeasurementResultId], [ValueType]),
    CONSTRAINT [FKMeasurementBlobsMeasurementResults] FOREIGN KEY ([MeasurementResultId]) REFERENCES [dbo].[MeasurementResults] ([Id]),
    CONSTRAINT [UQMeasurementBlobsId] UNIQUE ([Id])
)
GO

外键表:

CREATE TABLE [dbo].[MeasurementBlobsMeasurementClusters]
(
    [MeasurementResultId]   INT NOT NULL,
    [ValueType]             SMALLINT NOT NULL,
    [MeasurementClusterId]  INT NOT NULL,
    CONSTRAINT [PKMeasurementBlobsMeasurementClusters] PRIMARY KEY CLUSTERED ([MeasurementResultId], [ValueType]  ASC, [MeasurementClusterId] ASC),
    CONSTRAINT [FKMeasurementBlobsMeasurementClustersMeasurementBlob] FOREIGN KEY ([MeasurementResultId], [ValueType]) REFERENCES [dbo].[MeasurementBlobs] ([MeasurementResultId], [ValueType]),
    CONSTRAINT [FKMeasurementBlobsMeasurementClustersMeasurementCluster] FOREIGN KEY ([MeasurementClusterId]) REFERENCES [dbo].[MeasurementClusters] ([Id])
)
GO

每个类型继承使用表格不是一种选择。

1 个答案:

答案 0 :(得分:0)

问题是由外键表的主键引起的。

主键由三列组成,比外键需要多一列。以下是工作外键表定义:

CREATE TABLE [dbo].[MeasurementBlobsMeasurementClusters]
(
    [MeasurementResultId]   INT NOT NULL,
    [ValueType]             SMALLINT NOT NULL,
    [MeasurementClusterId]  INT NOT NULL,
    [IsFaultSource]         BIT NOT NULL,
    CONSTRAINT [PKMeasurementBlobsMeasurementClusters] PRIMARY KEY CLUSTERED ([MeasurementResultId], [ValueType]),
    CONSTRAINT [FKMeasurementBlobsMeasurementClustersMeasurementBlob] FOREIGN KEY ([MeasurementResultId], [ValueType]) REFERENCES [dbo].[MeasurementBlobs] ([MeasurementResultId], [ValueType]),
    CONSTRAINT [FKMeasurementBlobsMeasurementClustersMeasurementCluster] FOREIGN KEY ([MeasurementClusterId]) REFERENCES [dbo].[MeasurementClusters] ([Id])
)