c# - 为 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 }'.
是否可以使用实体配置创建索引?
解决方案
使用所有权构建器的流式 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 限制)。
推荐阅读
- .net-core - .Net Core 1.1 程序集中的重复类型名称
- java - 如何在spring数据mongo db中聚合一个嵌套对象并避免PropertyReferenceException?
- c# - 在本地运行单元测试时缺少文件
- r - 将当前数据框重塑为另一个数据框并创建新列(连接)
- node.js - 如何使用谷歌语音从长音频中获取文本到文本 node.js
- ruby - Ruby mediainfo(gem)错误“mon超出范围”?
- c++ - 如果同时运行,BIGSERIAL 事务是否安全?(PostgreSQL,libpqxx)
- excel - 如何将 application.vlookup 函数的结果显示为 TextBox.Value?
- sql-server - SQL Server Management Studio 未连接到服务器
- r - R 正则表达式删除除与此正则表达式匹配的数字之外的所有数字