我有以下两门课
public class Tip
{
public string Home { get; set; }
public string Away { get; set; }
public string Prediction { get; set; }
public Tipster Tipster { get; set; }
... other properties
}
public class Tipster
{
public int Id { get; set; }
public string Username { get; set; }
public string Platform { get; set; }
}
现在,我想在 theTip 表中创建唯一索引。根据 EF Core 文档,没有 Data Annotations 语法,因此我使用的是 Fluent 语法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Tip>()
.HasIndex(entity => new { entity.Tipster, entity.Home, entity.Away, entity.Prediction })
.HasName("IX_UniqueTip")
.IsUnique();
}
现在,当我更新数据库时,出现以下错误
C:..>dotnet ef 数据库更新 System.InvalidOperationException:
无法调用实体类型“Tip”上属性“Tipster”的属性
因为它被配置为导航属性。物业只能
用于配置标量属性。
EF 似乎不喜欢我在索引中使用引用属性这一事实。我该如何解决这个问题?
您不能在索引定义表达式中使用导航属性。相反,您应该使用相应的 FK 属性。
您的情况的问题是您的模型中没有显式的 FK 属性Tip
。按照惯例 EF Core 将创建int? TipsterId
影子财产 https://learn.microsoft.com/en-us/ef/core/modeling/shadow-properties。所以理论上你应该能够使用EF.Property
访问它的方法:
.HasIndex(e => new { TipsterId = EF.Property<int>(e, "TipsterId"), e.Home, e.Away, e.Prediction })
不幸的是,这目前不起作用(EF Core 2.0.1)。所以你必须求助于HasIndex
过载params string[] propertyNames
:
.HasIndex("TipsterId", nameof(Tip.Home), nameof(Tip.Away), nameof(Tip.Prediction))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)