user2625648
user2625648

Reputation: 71

Find index by using entity framework

I have Products

(index0)- Name=Computer, Id = 1

(index1)- Name=Mouse, Id= 2

(index2)- Name=Keyboard, Id = 3

(index3)- Name=Laptop, Id = 4

as instance,

var result = context.Products.where(s=>s.Id==3).firstordefault();

How can ı find Id=3 product's index by using entity framework in c# ?

Upvotes: 1

Views: 9015

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30454

You don't mention the type of your (index..) items, but let's assume it is an int. In fact it can be any type.

Your (index..) items are the primary key, let's assume they are in property Index:

Your Product class would be like:

class Product
{
    [Key]
    public int Index {get; set;}

    public string Name {get; set;}
    public int Id {get; set;}

    // etc.
 }

Your DbContext would be like:

public class MyDbContext : DbContext
{
    public DbSet<Product> Products {get; set;}
    ...
}

To get all products with Id == 3, and to get the Indices of these products:

using (var dbContext = new MyDbContext(...))
{
   var productsWithId3 = dbContext.Products
       .Where(product => product.Id == 3);
   var indicesOfProductsWithId3 = productsWithId3
       .Select(product => product.Index);
   // of course this can be done in one step

   // the query is not executed until you start enumerating
   foreach (var index in indicesOfProductsWithId3)
   {
       Console.WriteLine(index.ToString());
    }     
}

Be sure to enumerate your query before you end the using statement. Your compiler won't complain, however you'll get an exception at run-time

Upvotes: 0

Chris
Chris

Reputation: 8656

I'm not sure what you'd want to use the index for, and I don't think there's really a concept of index on a DBSet<TEntity>.

You could probably obtain an index from the Local property on your DBSet, using FindIndex:

 context.Products.Local.IndexOf(...)

But I'm sure there's a better approach to whatever you're trying to do.

Also, assuming Id is the primary key of your object if you know the ID of your object, you should probably use Find to obtain your entity:

var result = context.Products.Find(Id); // Id = 3.

Upvotes: 2

Related Questions