Required注释位于LessonQuestionDetails Entity-model中的一个导航属性中,它允许通过代码优先方法创建级联删除表,从而使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
}发布于 2018-12-29 18:13:48
您可以使用fluent API。
像下面这样的东西应该可以工作,但可能需要调整,就像在编辑器上写的那样,并没有测试它,但这是它的要点
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<LessonQuestion>()
.HasOptional(c => c.LessonQuestion)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}但是,直接在API中使用实体框架模型是一个错误的设计。
您应该为API所需的属性使用视图模型,然后将它们映射到实体框架模型。永远不要直接公开实体框架模型,因为它只会导致问题,更改实体框架模型将需要应用程序范围的更改,包括使用API的应用程序,这将成为维护的噩梦。
https://stackoverflow.com/questions/53972122
复制相似问题