问题:
我正在尝试使用数据库第一种方法创建EF6模型。简单来说,我有{2}个表tblUser
和tblMilkMan
,它们在UserID
列上具有外键关系。但是当我创建一个新的EDMX图并添加2个表时:
请告诉我我做错了什么!
数据库架构:
表脚本:
CREATE TABLE [dbo].[tblMilkMan]
(
[RecordID] [INT] NOT NULL
IDENTITY(1, 1) ,
[UserID] [INT] NOT NULL ,
[IsMyTurn] [BIT] NOT NULL ,
[RoundRobinOrder] [INT] NOT NULL
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[tblMilkMan] ADD CONSTRAINT [PK_tblMilkMan] PRIMARY KEY CLUSTERED ([RecordID]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tblMilkMan] ADD CONSTRAINT [FK__MilkMan__User__UserID] FOREIGN KEY ([UserID]) REFERENCES [dbo].[tblUser] ([UserID]) ON DELETE CASCADE
GO
CREATE TABLE [dbo].[tblUser]
(
[UserID] [INT] NOT NULL
IDENTITY(1, 1) ,
[LogonName] [VARCHAR](20) COLLATE SQL_Latin1_General_CP437_CI_AS
NOT NULL ,
[Client] [CHAR](4) COLLATE SQL_Latin1_General_CP437_CI_AS
NOT NULL ,
[Password] [VARCHAR](20) COLLATE SQL_Latin1_General_CP437_CI_AS
NOT NULL ,
[PasswordExpires] [DATETIME] NULL ,
[PasswordExpiresAfter] [INT] NOT NULL
CONSTRAINT [DF_tblUser_PasswordExpiresAfter] DEFAULT ( 9999 ) ,
[FirstName] [VARCHAR](20) COLLATE SQL_Latin1_General_CP437_CI_AS
NOT NULL ,
[LastName] [VARCHAR](20) COLLATE SQL_Latin1_General_CP437_CI_AS
NOT NULL
)
ON [PRIMARY]
WITH (
DATA_COMPRESSION = ROW)
GO
ALTER TABLE [dbo].[tblUser] ADD CONSTRAINT [PK_tblUser] PRIMARY KEY CLUSTERED ([UserID]) WITH (DATA_COMPRESSION = ROW) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_tblUser] ON [dbo].[tblUser] ([UserID]) WITH (FILLFACTOR=90, DATA_COMPRESSION = ROW) ON [PRIMARY]
GO
EDMX Designer查看:
有关我帮助的相关链接:
Why doesn't EF 4 generate association for FK relation to column with unique index?
EF does not generate foreign key association from foreign key in table
环境:
答案 0 :(得分:2)
问题是以下一行 -
CREATE UNIQUE NONCLUSTERED INDEX [IX_tblUser] ON [dbo].[tblUser] ([UserID])
WITH (FILLFACTOR=90, DATA_COMPRESSION = ROW) ON [PRIMARY]
GO
我不知道在同一列上有Clustered和NonClustered索引的原因。常见的最佳做法是将主键创建为聚簇索引。 (Source)
如果删除 NONCLUSTERED INDEX ,则会在EDMX中看到该关系。