【问题标题】:ModelState.IsValid is false due to the "required" navigation property in Entity由于 Entity 中的“必需”导航属性,ModelState.IsValid 为 false
【发布时间】:2019-05-27 01:57:10
【问题描述】:

LessonQuestionDetails中导航属性中的Required注解实体模型,支持通过代码优先方法创建级联删除表,导致ModelState.IsValid 变为false。没有Required 注释是否有解决方法来设置级联删除。

实体模型

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
}

【问题讨论】:

  • 您不需要必填字段。您可以使用流畅的 API 来做到这一点。你会在谷歌上找到很多参考
  • 什么有错误?

标签: c# asp.net-mvc entity-framework required modelstate


【解决方案1】:

您可以使用流畅的 API。

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多