how to check for entities/relationships generically

僤鯓⒐⒋嵵緔 提交于 2020-01-07 14:38:12

问题


I have entities/relationships like following A -> B; B -> C, B -> D, B -> E, ...

When a user wants to delete entity A, I check whether any of its children B entities have any records for C entities, and D entities, etc and provide a detailed error message.

However, the requirement is that we might end up adding more entity types such as B -> FutureEntity. Is there a way to either generically check for all of these, or atleast make sure that in the future if such an entity gets added, I modify the deletion functionality to account for such entities?


回答1:


You can achieve this by adding the following functions to the 'BaseEntity':

public abstract class BaseEntity
{

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

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

When you add a child entity override those methods:

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


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

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

Before you delete entity B, check the associated entities:

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()}");
}

Here is the function that checks for associated children:

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;
}


来源:https://stackoverflow.com/questions/56387368/how-to-check-for-entities-relationships-generically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!