首页 > 解决方案 > 由于 Entity 中的“必需”导航属性,ModelState.IsValid 为 false

问题描述

LessonQuestionDetails Entity-modelRequired中的 Navigation Property 中的注释,它允许通过代码优先方法创建级联删除表,导致成为. 是否有解决方法来设置没有注释的级联删除。 ModelState.IsValidfalseRequired

实体模型

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
}

控制器

[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
}

标签: c#asp.net-mvcentity-frameworkrequiredmodelstate

解决方案


您可以使用流畅的 API。

像下面这样的东西应该可以工作,但可能需要像在编辑器上写的那样进行调整并且没有测试它,但这就是它的要点

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

但是,直接将实体框架模型与您的 API 一起使用是一个糟糕的设计。

您应该为 API 所需的属性使用视图模型,然后将它们映射到您的实体框架模型。永远不要直接公开实体框架模型,因为它只会导致问题,并且更改实体框架模型将需要应用程序范围的更改,包括使用 API 的应用程序,这将成为维护的噩梦。


推荐阅读