ASP.MVC db Find(), but with non-primary key parameter

user picture user · Aug 31, 2013 · Viewed 25.1k times · Source

How does one get a list of results by using a key that is not the primary key? To be more specific, I have a composite primary key where I would like to retrieve all the matches with one column's parameter.

I would think, in an ActionResult in the Controller, it's something like

tableModel tbmodel = db.tableModels.Find(i => i.partialPK == parameter)

but that's not the case, since Find() only works with the entire PK.

I declared my PKs in the entity model class as:

    [Key]
    [Column(Order = 0)] 
    public int PK1 { get; set; }
    [Key]
    [Column(Order = 1)] 
    public string PK2 { get; set; }

Answer

PMC picture PMC · Aug 31, 2013

According to DbSet.Find you can pass in the primary keys separated by commas

db.tableModels.Find(PK1, PK2)

The Find method takes an array of objects as an argument. When working with composite primary keys, pass the key values separated by commas and in the same order that they are defined in the model.

However, if you want to just use one value, you will probably have to use

db.tableModels.Where(i => i.partialPK == parameter)

or an equivalent Linq operator