如何一般地检查实体/关系

时间:2019-05-31 00:49:47

标签: c# entity-framework-6 asp.net-core-2.0

我有类似A-> B的实体/关系; B-> C,B-> D,B-> E,...

当用户想要删除实体A时,我检查其子B实体中是否有C实体和D实体等的任何记录,并提供详细的错误消息。

但是,要求是我们最终可能会添加更多的实体类型,例如B-> FutureEntity。有没有办法对所有这些进行一般性检查,或者至少确保将来在添加了这样一个实体的情况下,我修改删除功能以解决这些实体?

1 个答案:

答案 0 :(得分:0)

您可以通过在'BaseEntity'中添加以下功能来实现此目的:

public abstract class BaseEntity
{

    [Key]
    public int Id { get; set; }

    public abstract bool IsChildOfBee();
    public abstract string GetDisplayName();
}

添加子实体时,请覆盖以下方法:

public class EntityCee :BaseEntity
{
    public string Name { get; set; }


    public override string GetDisplayName()
    {
        return "Entity Cee";
    }

    public override bool IsChildOfBee()
    {
        return true;
    }
}

在删除实体B之前,请检查关联的实体:

var errors = new List<string>();

var entityBeeToDelete = _exampleRepository.GetEntityBee(1);

var associatedEntities = _exampleRepository.GetAssociatedEntities(entityBeeToDelete);

foreach(var e in associatedEntities)
{
    errors.Add($"{entityBeeToDelete.GetDisplayName()} has some {e} records associated with it. Please delete those before deleting {entityBeeToDelete.GetDisplayName()}");
}

以下是检查关联子项的功能:

public List<string> GetAssociatedEntities(EntityBee bee)
{
    var types = new List<string>();

    foreach (var entityType in this.Model.GetEntityTypes())
    {
        var clr = entityType.ClrType;

        var tableName = entityType.Relational().TableName;

        BaseEntity instance = (BaseEntity)Activator.CreateInstance(clr);

        var isChildOfBee = instance.IsChildOfBee();

        if(isChildOfBee)
        {
            var query = $"select top(1) * from EntityBees where Id IN (select EntityBeeId from {tableName} where EntityBeeId = {bee.Id})";

            var eB = this.EntityBees.FromSql(query).FirstOrDefault();

            if(eB != null)
            {
                types.Add(instance.GetDisplayName());
            }

        }

    }
    return types;
}