Search code examples
c#entity-frameworkef-code-firstodata

OData request without part of composite primary key in url


I'm writing an application using EF6 Code First, and exposing my entities via OData endpoints. I have what is essentially a change tracking entity that keeps track of all previous values of another entity; something similar to the following:

public class QuizAnswerHistory
{
    [Key]
    public int StudentId { get; set; }
    [Key]
    public int QuestionId { get; set; }
    [Key]
    public DateTime ModifiedDate { get; set; }
    public string AnswerValue { get; set; }
}

I also have a QuizAnswer entity, which has exactly the same properties, except it's composite primary key doesn't include ModifiedDate. It references only a Student entity, and a Question entity.

Now, because I want to be able to get the entire QuizAnswerHistory entity for a specific Student/Question, I don't want to have to specify the ModifiedDate in my OData request.

However, because the ModifiedDate is a primary key, when I send a GET request to /odata/QuizAnswerHistory(StudentId=1,QuestionId=2), I get the error, "The number of primary key values passed must match number of primary key values defined on the entity."

Is it possible to keep the ModifiedDate as a primary key, but not require it in my requests?


Solution

  • There are 2 options to resolve the issue:

    1. Send a GET request to this URL: /odata/QuizAnswerHistory?$filter=StudentId eq 1 and QuestionId eq 2
    2. Using OData Function feature, but you need to upgrade from OData v3 to v4, where DateTime type is replace with DateTimeOffset. For Function sample, please refer:https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataFunctionSample/