Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an element in a DbSet with a composite primary key

Tags:

c#

asp.net-mvc

I have the following model and am trying to find a specific object in a DbSet:

public class UserSkill
{
    [Key, Column(Order = 1)]
    public int UserId { get; set; }

    [Key, Column(Order = 2)]
    [ForeignKey("Skill")]
    public int SkillId { get; set; }

    public virtual Skill Skill { get; set; }
}

I've tried the following two ways of finding a certain UserSkill object (I'm passing the DbSet of UserSkills via the ViewBag):

ViewBag.UserSkills.Find(new { WebSecurity.CurrentUserId, item.SkillId })
ViewBag.UserSkills.Find(new UserSkill(WebSecurity.CurrentUserId, item.SkillId))

But in both cases, I get an error:

The number of primary key values passed must match number of primary key values defined on the entity.

What am I missing? It seems to me that the primary key consists of two columns, and I'm providing the find function with the two values that comprise the primary key.

like image 696
jacobsowles Avatar asked Apr 26 '14 19:04

jacobsowles


2 Answers

The signature of Find method is TEntity Find(params Object[] keyValues) and you can enlist the keys of composite primary key in proper order.

ViewBag.UserSkills.Find(WebSecurity.CurrentUserId, item.SkillId )
like image 144
Hamlet Hakobyan Avatar answered Oct 18 '22 05:10

Hamlet Hakobyan


To find an entity by composite key you should use this overload

ViewBag.UserSkills.Find(WebSecurity.CurrentUserId, item.SkillId);

Msdn

like image 44
d_z Avatar answered Oct 18 '22 06:10

d_z