C
C#8mo ago
Core

✅ EF multicolumn index by only having navigational property in the model

Hi, I am trying to create a multicolumn index and a foreign key would be part of it. With the help of the navigation property I am able to specify the foreign key, but I am unable to create the index. The syntax of the HasIndex is wrong, explicit string value cannot be used.
c#
public class Dog
{
public Guid Id {get; set; }
public string Alias {get; set; }

public Owner Owner { get; set; } // navigation property
}
c#
public class Dog
{
public Guid Id {get; set; }
public string Alias {get; set; }

public Owner Owner { get; set; } // navigation property
}
c#
private static void Configure(EntityTypeBuilder<Dog> builder)
{
builder.HasOne(b => b.Owner)
.WithMany()
.HasForeignKey("OwnerId");

builder.HasIndex(b => new { "OwnerId", b.Alias }) // Can't do this, but this is what I want to achieve
.IsUnique();
}
c#
private static void Configure(EntityTypeBuilder<Dog> builder)
{
builder.HasOne(b => b.Owner)
.WithMany()
.HasForeignKey("OwnerId");

builder.HasIndex(b => new { "OwnerId", b.Alias }) // Can't do this, but this is what I want to achieve
.IsUnique();
}
2 Replies
Keswiik
Keswiik8mo ago
You can define an explicit OwnerId foreign key property and use that to build your index
Core
CoreOP8mo ago
Thanks! That works
Want results from more Discord servers?
Add your server