EF6不从数据库生成外键关联

时间:2015-01-07 16:41:15

标签: c# sql-server entity-framework entity-framework-6 foreign-key-relationship

问题:

我正在尝试使用数据库第一种方法创建EF6模型。简单来说,我有{2}个表tblUsertblMilkMan,它们在UserID列上具有外键关系。但是当我创建一个新的EDMX图并添加2个表时:

  1. 我没有看到这段关系
  2. 未创建导航属性
  3. 请告诉我我做错了什么!

    数据库架构:

    ER Diagram

    表脚本:

    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查看:

    VS2012 View

    有关我帮助的相关链接:

    环境:

    • Visual Studio Ultimate 2012
    • SQL Server 2014
    • EF6
    • Web API2

1 个答案:

答案 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中看到该关系。

如何删除它?

enter image description here

enter image description here