使用EF Core如何强制使用模型属性之间的任何一种关系? [英] How do I enforce an either-or relationship between model properties, using EF Core?

查看:345
本文介绍了使用EF Core如何强制使用模型属性之间的任何一种关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是EF Core。

I'm using EF Core.

我的客户实体具有属性 Address1 Address2 AddressFull

My Customer entity has properties Address1, Address2, and AddressFull.

根据哪个系统向我发送数据,我可能会收到 Address1 Address2 ,否则我可能会收到 AddressFull

Depending on which system sends me the data, I may receive Address1 and Address2, or I may receive AddressFull.

所以我需要:


  • 需要 Address1 Address2 ,而 AddressFull 不需要

  • Address1 Address2 不需要,和 AddressFull 需要

  • EITHER Address1 and Address2 required, and AddressFull not-required
  • OR Address1 and Address2 not-required, and AddressFull required

所以我有:

  entityTypeBuilder.Property(p => p.Address1).IsRequired(false);
  entityTypeBuilder.Property(p => p.Address2).IsRequired(false);
  entityTypeBuilder.Property(p => p.AddressFull).IsRequired(false);

但是这个配置没有正确映射到我的域,我想强制执行逻辑。一般来说,实现这种类型的复杂域逻辑有两种方法。

But this config does not properly map to my domain, and I want to enforce the logic. Is that possible in EF Core?

推荐答案

您可以使用 CHECK 约束或触发器在数据库中执行此操作,也可以在域对象中执行此操作,并在 SaveChanges 。以下是后者的一个例子。

In general, there are two ways to implement this type of complex domain logic. You can do it in the database using CHECK constraints or triggers, or you can do it in your domain objects and check them during SaveChanges. Here is an example of the latter.

class MyEntity : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrEmpty(Address1)
            && string.IsNullOrEmpty(Address2)
            && string.IsNullOrEmpty(AddressFull))
        {
            yield return new ValidationResult("An address is required.");
        }
    }
}

class MyContext : DbContext
{
    public override int SaveChanges()
    {
        var entities = from e in ChangeTracker.Entries()
                       where e.State == EntityState.Added
                           || e.State == EntityState.Modified
                       select e.Entity;
        foreach (var entity in entities)
        {
            var validationContext = new ValidationContext(entity);
            Validator.ValidateObject(entity, validationContext);
        }

        return base.SaveChanges();
    }
}

这篇关于使用EF Core如何强制使用模型属性之间的任何一种关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆