如何配置EF Core-到同一表的两个关系

时间:2019-04-04 10:47:35

标签: c# foreign-keys entity-framework-core one-to-one ef-fluent-api

我正在尝试构建一个简单的消息传递应用程序以尝试测试实体框架核心,但是我无法正确使用OnModelCreating()方法。任何帮助将不胜感激。

我有两个模型,如下所示:

public class User
    {
        public long UserID { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public bool IsOnline { get; set; }
        public DateTime LastOnlineAt { get; set; }
        public bool IsVerified { get; set; }
        public string VerificationCode { get; set; }
        public ICollection<Message> Messages { get; set; }
    }

public class Message
    {
        public long MessageID { get; set; }
        public string Content { get; set; }
        public DateTime SentAt { get; set; }
        public bool IsRead { get; set; }
        public DateTime? ReadAt { get; set; }


        //Having Trouble Mapping These Two
        public long SentByUserID { get; set; }
        public User SentByUser { get; set; }
        public long SentToUserID { get; set; }
        public User SentToUser { get; set; }
    }

我尝试了以下OnModelCreate()

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<User>()
         .HasMany(u => u.Messages);

     modelBuilder.Entity<Message>()
         .HasOne(m => m.SentByUser);

     modelBuilder.Entity<Message>()
         .HasOne(m => m.SentToUser);
}

我想要的结果sql表是:

          User                           Message
-------------------------       ------------------------     
UserID {PK}                      MessageID {PK}
                                 SentToUserID {FK}
                                 SentByUserID {FK}

但是当我Update-Database

时,我继续收到以下错误消息
Failed executing DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Messages] (
    [MessageID] bigint NOT NULL IDENTITY,
    [Content] nvarchar(max) NULL,
    [SentAt] datetime2 NOT NULL,
    [IsRead] bit NOT NULL,
    [ReadAt] datetime2 NULL,
    [SentByUserID] bigint NOT NULL,
    [SentToUserID] bigint NOT NULL,
    [UserID] bigint NULL,
    CONSTRAINT [PK_Messages] PRIMARY KEY ([MessageID]),
    CONSTRAINT [FK_Messages_Users_SentByUserID] FOREIGN KEY ([SentByUserID]) REFERENCES [Users] ([UserID]) ON DELETE CASCADE,
    CONSTRAINT [FK_Messages_Users_SentToUserID] FOREIGN KEY ([SentToUserID]) REFERENCES [Users] ([UserID]) ON DELETE CASCADE,
    CONSTRAINT [FK_Messages_Users_UserID] FOREIGN KEY ([UserID]) REFERENCES [Users] ([UserID]) ON DELETE NO ACTION
);

Introducing FOREIGN KEY constraint 'FK_Messages_Users_SentToUserID' on table 'Messages' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

0 个答案:

没有答案