如何在Entity Framework代码优先方法中映射自我递归关系 [英] How to map recursive relation on self in Entity Framework code-first approach

查看:134
本文介绍了如何在Entity Framework代码优先方法中映射自我递归关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我想要创建的是基本的递归类别。如果 RootCategory_Id 设置为null,则属性为root,如果设置为某个id,则属于某个其他类别。我已经在 Seed()方法中添加了两个子类别的类别进行测试,它不起作用。 (我已经检查过DB,有插入)

All I want to create is basic recursive category. Category is root if RootCategory_Id is set to null and it belongs to some other category if it is set to some id. I've added category with two child-categories in Seed() method to test and it does not work. (I've checked DB afterwards, there are inserted)

public class Category
{
    public int ID { get; set; }
    public Category RootCategory { get; set; } // This one works good, it also creates "RootCategory_Id" in database on "update-database"

    public ICollection<Category> ChildCategories { get; set; } // This is always null, how to map it correctly?

    public string Name { get; set; }
}



种子方法



Seed method

protected override void Seed(Test.Infrastructure.TestDataContext context)
{
    context.Categories.Add(new Category() {
        Name = "First Category", ChildCategories = new List<Category>() {
            new Category(){
                Name = "Second Category"
            },
            new Category(){
                Name = "Third Category"
            }
        }
    });

    context.SaveChanges();
}



这是我测试它不工作的方式



This is how I tested that it does not work

public ActionResult Test()
{
    // After checking DB my root is 4, and two categories that have RootCategory_Id set to 4
    var c = _db.Categories.Where(x => x.ID == 4).Single();
    return Content(c.ChildCategories.FirstOrDefault().Name); // Always returns null, even c.ChildCategories.Count() returns 'null'
}



< h3>我想要实现的图片

这是从使用linq-to-sql的数据库优先方法生成的


Picture of what I want to achieve

this was generated from database-first approach using linq-to-sql

推荐答案

我真的不想在这里进行necro-thread,但是我一直在寻找如何解决这个确切问题的方法。

I didn't really want to necro-thread here, but I've been searching for methods on how to solve this exact problem.

这是我的解决方案它有点长,但它允许一个更加可扩展的方法来进行Code First编程。它还引入了策略模式,允许SoC尽可能保持为POCO。

Here's my solution; it's a bit long winded, but it allows a much more scalable approach to Code First programming. It also introduces the Strategy pattern to allow for SoC while remaining as POCO as possible.

IEntity接口

/// <summary>
///     Represents an entity used with Entity Framework Code First.
/// </summary>
public interface IEntity
{
    /// <summary>
    ///     Gets or sets the identifier.
    /// </summary>
    /// <value>
    ///     The identifier.
    /// </value>
    int Id { get; set; }
}

IRecursiveEntity接口

/// <summary>
///     Represents a recursively hierarchical Entity.
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public interface IRecursiveEntity <TEntity> where TEntity : IEntity
{
    /// <summary>
    ///     Gets or sets the parent item.
    /// </summary>
    /// <value>
    ///     The parent item.
    /// </value>
    TEntity Parent { get; set; }

    /// <summary>
    ///     Gets or sets the child items.
    /// </summary>
    /// <value>
    ///     The child items.
    /// </value>
    ICollection<TEntity> Children { get; set; }
}

实体抽象类

/// <summary>
///     Acts as a base class for all entities used with Entity Framework Code First.
/// </summary>
public abstract class Entity : IEntity
{
    /// <summary>
    ///     Gets or sets the identifier.
    /// </summary>
    /// <value>
    ///     The identifier.
    /// </value>
    public int Id { get; set; }
}

递归实例抽象类:

/// <summary>
///     Acts as a base class for all recursively hierarchical entities.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
public abstract class RecursiveEntity<TEntity> : Entity, IRecursiveEntity<TEntity> 
    where TEntity : RecursiveEntity<TEntity>
{
    #region Implementation of IRecursive<TEntity>

    /// <summary>
    ///     Gets or sets the parent item.
    /// </summary>
    /// <value>
    ///     The parent item.
    /// </value>
    public virtual TEntity Parent { get; set; }

    /// <summary>
    ///     Gets or sets the child items.
    /// </summary>
    /// <value>
    ///     The child items.
    /// </value>
    public virtual ICollection<TEntity> Children { get; set; }

    #endregion
}

注意: 有些人建议您修改关于这个课程的这篇文章。该类只需要接受 RecursiveEntity< TEntity> 作为约束,而不是 IEntity ,以使其仅限于处理递归实体。这有助于缓解类型不匹配的异常。如果您使用 IEntity ,则需要添加一些异常处理来计算不匹配的基类型。

Note: Some people have suggested edits to this post regarding this class. The class needs to only accept RecursiveEntity<TEntity> as a constraint, rather than IEntity so that it is constrained to only handle recursive entities. This helps alleviate type mismatch exceptions. If you use IEntity instead, you will need to add some exception handling to counter mismatched base types.

使用 IEntity 将提供完美有效的代码,但在任何情况下都不会按预期方式工作。使用可用的最上层根源并不总是最佳做法,在这种情况下,我们需要进一步限制继承树,而不是根层级。我希望这是有道理的。这是我开始玩的东西,但在填充数据库时我遇到了很大的问题;特别是在实体框架迁移期间,您没有细粒度的调试控制。

Using IEntity will give perfectly valid code, but it will not work as expected under all circumstances. Using the topmost root available, isn't always the best practice, and in this case, we need to constrain further down the inheritence tree than at that root level. I hope that makes sense. It is something I played around with at first, but I had huge problems when populating the database; especially during Entity Framework Migrations, where you have no fine grained debugging control.

在测试期间,它似乎也不会很好用 IRecursiveEntity< ; TEntity> 。我很快就会回来,因为我正在刷新一个使用它的旧项目,但它在这里写的方式是完全有效和有效的,我记得调整它,直到它按预期工作。我认为在代码优雅和继承性方法之间有一个权衡,使用更高级的类意味着在 IEntity IRecursiveEntity < IEntity> ,反过来表现较差,看起来很丑陋。

During testing, it also didn't seem to play nice with IRecursiveEntity<TEntity> either. I may return to this soon, as I'm refreshing an old project that uses it, but the way it is written here is fully valid and working, and I remember tweaking it until it worked as expected. I think there was a trade off between code elegance and inheritance heirarchy, where using a higher level class meant casting a lot of properties between IEntity and IRecursiveEntity<IEntity>, which in turn, gave a lower performance and looked ugly.

我使用原始问题的示例...

I've used the example from the original question...

类别混合类:

public class Category : RecursiveEntity<Category>
{
    /// <summary>
    ///     Gets or sets the name of the category.
    /// </summary>
    /// <value>
    ///     The name of the category.
    /// </value>
    public string Name { get; set; }
}

我已经从类中除去了非派生属性。 类别从其自我关联的 RecursiveEntity 类的通用继承中导出所有其他属性。

I've stripped out everything from the class apart from non-derived properties. The Category derives all its other properties from its self-associated generic inheritance of the RecursiveEntity class.

为了使整个事情更具管理性,我添加了一些扩展方法轻松添加新的孩子到任何父项目。我发现,这个困难是你需要设置一对多关系的两端,只是把孩子加入到列表中,不允许你按照他们的意图处理它们。这是一个简单的修复,从长远来看节省了大量的时间。

To make the whole thing more managable, I've added some extension methods to easily add new children to any parent item. The difficulty, I found, was that you need to set both ends of the one-to-many relationship and merely adding the child to the list didn't allow you to handle them in the way they are intended. It's a simple fix that saves a huge amount of time in the long run.

RecursiveEntityEx静态类:

/// <summary>
///     Adds functionality to all entities derived from the RecursiveEntity base class.
/// </summary>
public static class RecursiveEntityEx
{
    /// <summary>
    ///     Adds a new child Entity to a parent Entity.
    /// </summary>
    /// <typeparam name="TEntity">The type of recursive entity to associate with.</typeparam>
    /// <param name="parent">The parent.</param>
    /// <param name="child">The child.</param>
    /// <returns>The parent Entity.</returns>
    public static TEntity AddChild<TEntity>(this TEntity parent, TEntity child)
        where TEntity : RecursiveEntity<TEntity>
    {
        child.Parent = parent;
        if (parent.Children == null)
            parent.Children = new HashSet<TEntity>();
        parent.Children.Add(child);
        return parent;
    }

    /// <summary>
    ///     Adds child Entities to a parent Entity.
    /// </summary>
    /// <typeparam name="TEntity">The type of recursive entity to associate with.</typeparam>
    /// <param name="parent">The parent.</param>
    /// <param name="children">The children.</param>
    /// <returns>The parent Entity.</returns>
    public static TEntity AddChildren<TEntity>(this TEntity parent, IEnumerable<TEntity> children)
        where TEntity : RecursiveEntity<TEntity>
    {
        children.ToList().ForEach(c => parent.AddChild(c));
        return parent;
    }
}

一旦你有了所有这一切,你可以因此种子:

Once you have all of that in place, you can seed it thusly:

种子方法

/// <summary>
///     Seeds the specified context.
/// </summary>
/// <param name="context">The context.</param>
protected override void Seed(Test.Infrastructure.TestDataContext context)
{
    // Generate the root element.
    var root = new Category { Name = "First Category" };

    // Add a set of children to the root element.
    root.AddChildren(new HashSet<Category>
    {
        new Category { Name = "Second Category" },
        new Category { Name = "Third Category" }
    });

    // Add a single child to the root element.
    root.AddChild(new Category { Name = "Fourth Category" });

    // Add the root element to the context. Child elements will be saved as well.
    context.Categories.AddOrUpdate(cat => cat.Name, root);

    // Run the generic seeding method.
    base.Seed(context);
}

这篇关于如何在Entity Framework代码优先方法中映射自我递归关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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