EF复杂类让我无效

时间:2014-10-28 15:09:35

标签: c# entity-framework asp.net-mvc-5

我有一个这样的课。

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public IList<Role> Roles { get; set; }
    public virtual Branch Branch { get; set; }
    public string Password { get; set; }
}

public class Branch
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public virtual Region Region { get; set; }
}

我遇到的问题是,当我将user作为参数传递给存储库层时,Branch属性显示为null。我已经验证过,在它到达存储库之前,它不是空的。我认为是序列化的东西,但我不知道如何解决它。

提前致谢!

这是存储库获取对象的方式:

public readonly IDbSet<T> DbSet;
public IEnumerable<T> Find(Expression<Func<T, bool>> predicate, string sortColumn = null, bool sortDirection = true, params  string[] includes)
    {
        if (sortColumn == null)
        {
            var resultSet = GetDbSet(includes).Where(predicate);
            resultSet.ForEachAsync(e => Detach(e)).Wait();
            return resultSet;
        }
        else
            return OrderByField<T>(GetDbSet(includes).Where(predicate), sortColumn, sortDirection);
    }
    private IQueryable<T> GetDbSet(params string[] includes)
    {
        IQueryable<T> resultSet = DbSet;

        foreach (string include in includes)
            resultSet = resultSet.Include(include);

        return resultSet;
    }

    private T Detach(T entity)
    {
        System.Diagnostics.Contracts.Contract.Requires(entity != null);

        var entry = Context.Entry(entity);
        entry.State = System.Data.Entity.EntityState.Detached;
        return entity;
    }

1 个答案:

答案 0 :(得分:0)

我已经解决了。问题出在我一直在使用的通用存储库上。当它获取条目时,将条目设置为Detached,并在我传递到存储库进行保存时导致null。我删除了分离方法,一切正常。