为OwnesOne导航属性创建索引

让我们看看下一个示例:

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Client Client { get; set; }
}

public class Client
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我有实体配置的下一部分:

builder.OwnsOne(x => x.Client,client =>
{
    client.Property(x => x.Id).isrequired(false);
    client.Property(x => x.Name).isrequired(false);
});

如果将迁移应用于数据库,我们将看到一个带有列Blogs的表Client_Id

现在,我想为此列创建索引。我在实体配置中添加了下一行。

builder.HasIndex(x => x.Client.Id);

如果您尝试创建迁移,则会看到下一个错误:

System.Reflection.TargetinvocationException: Exception has been thrown by the target of an invocation.
---> System.ArgumentException: The properties expression 'x => Convert(x.Client.Id,Object)' is not valid.
The expression should represent a simple property access: 't => t.MyProperty'.
When specifying multiple properties use an anonymous type: 't => new { t.MyProperty1,t.MyProperty2 }'.

是否可以使用实体配置创建索引?

zhanjial 回答:为OwnesOne导航属性创建索引

使用所有权构建器的流畅API为每种所有者类型分别配置拥有类型。

您可以使用配置属性的相同方式来创建索引,例如

builder.OwnsOne(x => x.Client,client =>
{
    client.Property(x => x.Id).IsRequired(false);
    client.Property(x => x.Name).IsRequired(false);

    client.HasIndex(x => x.Id); // <--
});

唯一的潜在问题是,如果您需要使用所有者和拥有者类型的字段来创建复合索引,我认为这目前是不可能的(当前EF Core限制)。

本文链接:https://www.f2er.com/3165009.html

大家都在问