【问题标题】:How to in .Net core domain model replace validation of primitive types with value objects?如何在.Net核心域模型中用值对象替换原始类型的验证?
【发布时间】:2020-02-29 08:02:12
【问题描述】:

.Net Core 3

通过thisthis 示例,我尝试使用值对象创建域模型的验证。 但我得到了错误。

// Value object TitleValue
 public class TitleValue : ValueObject
    {

        public string Value { get; }

        public TitleValue()
        {
        }

        public TitleValue(string value)
        {
            Value = value;
            Create(value);
        }

        public static Result<TitleValue> Create(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
                return Result.Fail<TitleValue>(Errors.General.ValueIsRequired().Serialize());

            string title = input.Trim();

            if (title.Length > 2)
                return Result.Fail<TitleValue>(Errors.General.ValueIsTooLong().Serialize());



            return Result.Ok(new TitleValue(title));
        }


        protected override IEnumerable<object> GetEqualityComponents()
        {
            yield return Value;
        }
    }
// Domain model 
 public class Navigation
    {
        [Key]
        public int Id { get; set; }

        public TitleValue Title { get; set; } // there is problem
        public string Slug { get; set; }
        public byte IsCategory { get; set; }
        public int Sort { get; set; }
        public int Parent { get; set; }
        public string Path { get; set; }
        public ICollection<EdRoleNavigation> RoleNavigations { get; set; }
    }

我得到错误:

处理请求时发生未处理的异常。 InvalidOperationException:实体类型“TitleValue”需要定义主键。如果您打算使用无密钥实体类型,请调用“HasNoKey()”。 Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel 模型,IDiagnosticsLogger 记录器)

.Net 核心认为,TitleValue 是一个实体。

如何修复此错误并获得良好的验证?

【问题讨论】:

    标签: c# asp.net-core domain-driven-design


    【解决方案1】:
    【解决方案2】:

    你必须告诉 EF TitleValue 是一个值对象。

    OnModelCreating:

        builder.Entity<Navigation>().OwnsOne(n => n.TitleValue, n => n.Property(p => p.Value).HasColumnName("Title"));
    

    IEntityTypeConfiguration.Configure:

        builder.OwnsOne(n => n.TitleValue, n => n.Property(p => p.Value).HasColumnName("Title"));
    

    其中OwnsOneTitleValue 设置为值对象(问题已解决)。

    第二个表达式告诉 EF 您想要名为“Title”的数据库列,而不是默认的“Title_Value”。

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 1970-01-01
      • 2021-10-14
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2017-05-28
      • 2015-12-19
      相关资源
      最近更新 更多