Domanda

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; }
È stato utile?

Soluzione

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

Altri suggerimenti

If you're trying to get the object with linq query from database, use: .FirstOrDefault with .Where

Customer customer = db.Customers.Where(c => c.Email == auth.Email).FirstOrDefault();

Here db is DbContext and Customer is the DbSet

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top