How to Find a record in Entity Framework without a Primary Key

entity-framework-core

Question

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.

1
0
9/23/2018 2:25:05 PM

Popular Answer

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.

0
9/23/2018 4:13:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow