问题:大家好。我正在使用EF核心2.1,我需要在表中InstallationInformation属性LicenceKey和Importrun(FK)到一个唯一的索引(组合)。
补充信息:如果我所做的研究是正确的。我不能在.net核心2.1中使用注释索引,因为它不受支持。我试着升级,但它需要VS 2019,而我没有。要使用VS 2019,我需要Windows10,我也没有使用它。
我尝试过的方法。我尝试了注解的事情。但不幸的是,它不起作用。我发现我可以尝试使用Fluent API,并发现我可以映射该属性。
modelBuilder.Entity<InstallationInformation>(entity =>
{
entity.HasIndex(i => new { i.LicenceKey, i.ImportRun }).IsUnique();
});但在我进行调试时,它出现了这个错误:"InvalidOperationException:'ImportRun‘不能用作实体类型'InstallationInformation’的属性,因为它被配置为导航。“
代码结构:
public class ImportRun
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ImportRunId { get; set; }
public DateTime ExtractedDate { get; set; }
public DateTime ProcessDate { get; set; }
public ResultCondition ProcessResult { get; set; }
public string FailureDescription { get; set; }
[Required]
public virtual ICollection<InstallationInformation> InstallationInformation { get; set; }
}public class InstallationInformation
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int InstallationInformationID { get; set; }
[MaxLength(256)]
public string LicenceKey { get; set; }
[MaxLength(256)]
public string ProductVersion { get; set; }
[MaxLength(256)]
public string ProductName { get; set; }
[MaxLength(256)]
public string CompanyName { get; set; }
public DateTime Timestamp { get; set; }
[Required]
public ImportRun ImportRun { get; set; }
}protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ImportRun>()
.HasMany(c => c.InstallationInformation)
.WithOne(e => e.ImportRun)
.IsRequired();
modelBuilder.Entity<InstallationInformation>(entity =>
{
entity.HasIndex(i => new { i.LicenceKey, i.ImportRun }).IsUnique();
});
}发布于 2020-07-08 09:41:50
更改:
modelBuilder.Entity<InstallationInformation>(entity =>
{
entity.HasIndex(i => new { i.LicenceKey, i.ImportRun }).IsUnique();
});至:
modelBuilder.Entity<InstallationInformation>(entity =>
{
entity.HasIndex(i => new { i.LicenceKey, i.ImportRunId }).IsUnique();
});https://stackoverflow.com/questions/60844818
复制相似问题