c# - 由于 Entity 中的“必需”导航属性,ModelState.IsValid 为 false
问题描述
LessonQuestionDetails Entity-modelRequired
中的 Navigation Property 中的注释,它允许通过代码优先方法创建级联删除表,导致成为. 是否有解决方法来设置没有注释的级联删除。 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。
像下面这样的东西应该可以工作,但可能需要像在编辑器上写的那样进行调整并且没有测试它,但这就是它的要点
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<LessonQuestion>()
.HasOptional(c => c.LessonQuestion)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
但是,直接将实体框架模型与您的 API 一起使用是一个糟糕的设计。
您应该为 API 所需的属性使用视图模型,然后将它们映射到您的实体框架模型。永远不要直接公开实体框架模型,因为它只会导致问题,并且更改实体框架模型将需要应用程序范围的更改,包括使用 API 的应用程序,这将成为维护的噩梦。
推荐阅读
- php - 在phpspreadsheet中完成写入列后如何下一个列?
- json - Angular i18n 和参数
- ruby - Ruby webscraping watir,webdrivers 无法连接到 chromedriver
- android - 在 android studio 中找不到打开的翻译编辑器
- neovim - 运行neovim的问题
- python - 如何将 django-clever-selects 用于过滤器而不是表单?
- swift - 如何在 ViewModel 中使用带有自定义类型和 @Published 的 @AppStorage?
- amazon-web-services - Attach PersistentVolume in a new node in Kubernetes
- umbraco8 - Umbraco:根级别的数据无效。第 1 行,位置 1
- ios - 推送另一个视图控制器时导航栏中的大标题出现故障