在EF Core中是否可以使单向导航属性成为必需的? [英] Is it possible in EF Core to make a one-way navigation property required?

查看:98
本文介绍了在EF Core中是否可以使单向导航属性成为必需的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个基本的群聊系统,我为它创建了以下类:

public class Role
{
    public Guid Id { get; set; };
    public string Username { get; set; }
}

public class Message
{
    public Guid Id { get; set; };
    public Role Author { get; set; }
    public Conversation Conversation { get; set; }
    public DateTime Date { get; set; }
    public string Text { get; set; }
}

public class Conversation
{
    public Guid Id { get; set; };
    public IList<ConversationParticipant> ConversationParticipants { get; set; };
    public IList<Message> Messages { get; set; };
}

public class ConversationParticipant
{
    public Conversation Conversation { get; set; }
    public Role Role { get; set; }
}

我们正在将EF Core 3.1 Code-First用于迁移。

我正在寻找一种方法使Message.Author成为必需的属性,这将导致表Message中的一个列被创建为AuthorId NOT NULL

我已尝试:

public static void Map(this EntityTypeBuilder<Message> builder)
{
    builder.HasOne(m => m.Author);
}

由于这是使用添加-迁移和更新-数据库应用的,因此创建了数据库列AuthorId,但允许NULL

似乎没有方法IsRequired()可以添加到HasOne()之后。

我也试过了:

public static void Map(this EntityTypeBuilder<Message> builder)
{
    builder.Property(m => m.Author).IsRequired();
}

但这并不能说明

属性‘Message.Author’的类型为‘Role’,当前数据库提供程序不支持该类型。更改属性CLR类型或使用‘[NotMaps]’特性或通过使用‘OnModelCreating’中的‘EntityTypeBuilder.Ignore’忽略该属性。

先执行.HasOne(...)再执行.Property(...).IsRequired()也不起作用:

"Author"不能用作实体类型"Message"的属性,因为它被配置为导航。

我设法使Message.Conversation成为必需的:

public static void Map(this EntityTypeBuilder<Conversation> builder)
{
    builder.HasMany(c => c.Messages)       // A conversation can have many messages
           .WithOne(e => e.Conversation)   // Each message belongs to at most 1 conversation
           .IsRequired();                  // A message always has a conversation
}

但是,我不想让Role知道消息,因为我永远不想直接从角色检索消息(这将通过对话和参与者进行)。

我的最终问题是:有没有一种方法可以使Message.Author成为必需的(非空),而不使用Role中的Messages属性将MessageRole链接在一起形成完全的一对多关系?

推荐答案

如何将Role的外键添加到Message,然后要求该属性不为空?类似于:

// MessageConfiguration.cs
builder.Property(b => b.RoleId).IsRequired()

这篇关于在EF Core中是否可以使单向导航属性成为必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆