【问题标题】:EF provider specific model configuration (if true then required)EF 提供程序特定模型配置(如果为 true,则需要)
【发布时间】:2019-11-12 18:01:56
【问题描述】:

仅当标志为真时如何设置为必需?

例如:

Property(t => t.DataQualityReview)
.If(t.IsDataQualityReview == true)
.ThenIsRequired()

【问题讨论】:

    标签: .net entity-framework-core ef-core-2.0


    【解决方案1】:

    我认为数据库将无法强制执行这种约束。 您可以通过多种方式以不同的方式强制执行要求。

    选项 1(首选): 如果您可以更改数据库的架构,则可以创建一个单独的实体/表来表示DataQualityReview

    public class Foo
    {
        // optional DataQualityReview
        public int? DataQualityReviewId { get; set; }
        public DataQualityReview DataQualityReview { get; set; }
    }
    public class DataQualityReview
    {
        public int DataQualityReviewId { get; set; }
    
        // required properties of a review
        public string Comments { get; set; }
        public int Rating { get; set; }
    }
    

    这里的想法是Foo 可能有也可能没有DataQualityReview。如果它确实有审核,那么您可以强制执行其他应该需要的属性(例如 CommentsRating 等)。

    选项 2:如果您无法更改数据库。您可以在类本身上强制执行此操作。

    public class Foo
    {
        // notice `private set`
        public bool IsDataQualityReview { get; private set; }
        public string DataQualityReview { get; private set; }
    
        public void UpdateReview(string review)
        {
          DataQualityReview = review;
          IsDataQualityReview = review != null;
        }
    }
    

    如图所示,您无法在Foo 之外更改IsDataQualityReviewDataQualityReview。然后,您公开一个方法 UpdateReview,它会根据评论更改这两个属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-02
      • 2010-12-11
      • 2020-04-22
      • 2021-10-27
      • 1970-01-01
      • 2021-12-24
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多