Sujoy
Sujoy

Reputation: 1217

ModelState.IsValid is false due to the "required" navigation property in Entity

The Required annotation in a Navigation Property in LessonQuestionDetails Entity-model, which enables Cascade-delete table creation through code-first approach, is causing ModelState.IsValid to become false. Is there a workaround to set cascade delete without the Required annotation.

Entity-model

public partial class LessonQuestionDetail
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int LessonID { get; set; }

    [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int QuestionNumber { get; set; }

    [Key, Column(Order = 2), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public byte ChoiceNumber { get; set; }
    public string Choice { get; set; }
    public bool IsCorrect { get; set; }

    [Required]  // Sets the CASCADE constraint, while creating table
    public virtual LessonQuestion LessonQuestion { get; set; }
}

public partial class LessonQuestion
{
    public LessonQuestion()
    {
        this.LessonQuestionDetails = new List<LessonQuestionDetail>();
    }

    public virtual ICollection<LessonQuestionDetail> LessonQuestionDetails { get; set; }
    //Other code
}

Controller

[HttpPost]
public ActionResult EditLessonQuestionDetails(LessonQuestion lq)
{
    SQLContext context = new SQLContext();
    int intChoiceNum=1;
    var errors = ModelState.Values.SelectMany(v => v.Errors); // There are errors
    var valid = ModelState.IsValid;  // sets False
    // Other code
}

Upvotes: 1

Views: 798

Answers (1)

npo
npo

Reputation: 1060

You can use the fluent API.

Something like below should work but might require tweaking as wrote it on the editor and didn't test it but that's the gist of it

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entity<LessonQuestion>()
        .HasOptional(c => c.LessonQuestion)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
 }

But, it's a bad design to use the Entity Framework models with your API directly.

You should use view models for the properties required by your API then map them to your Entity Framework models. Never expose the Entity Framework model directly as it only leads to problems and changing your Entity Framework model will require application wide changes including the applications that use the API which becomes a nightmare to maintain.

Upvotes: 3

Related Questions