I've got an entity:
public class Account
{
public int AccountId { get; set; }
public string Mnemonic { get; set; }
public decimal NetAssetValue { get; set; }
}
On this entity I have a primary key (AccountId) and an alternate unique index on the mnemonic.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Account
modelBuilder.Entity<Account>()
.HasKey(a => a.AccountId);
modelBuilder.Entity<Account>()
.HasIndex(a => a.Mnemonic)
.IsUnique();
}
When I store my test data in an XML file, I have no knowledge of the value assigned to the primary key, so I need to find this record by the Mnemonic if I want to use it. I know I can use LINQ:
var accountId = (from a in account
where mnemonic = "Account1"
select AccountId).First();
But will this use the index or iterate over the entire collection. I could have thousands of accounts and don't want do be executing a table scan each time I want to find an account when I'm loading from my external files.
Provided account
is the DbSet<Account>
from your DbContext
or an IQueryable<Account>
derived from he same, it will query the database using the index. if you want to emulate Find
(where the locally tracked entities are checked for the entity prior to querying the database) you can first check if dbContext.Set<Account>().Local
contains the entity prior to querying the database.