EntityFramework中的错误? .Include和Parameterless构造函数

时间:2011-08-17 01:10:03

标签: c# entity-framework code-first

简要背景:

使用数据库优先/仅代码(虽然我认为不重要)

基本设置如下:

public class MyContext : DbContext
{
    public DbSet<MyClass_MyClasses> MyClass_MyClasses { get; set; }
    public DbSet<MyClass> MyClasses { get; set; }
}

public class MyClass_MyClasses
{
    [Key]
    [Column(Order = 0)]
    public Guid ParentId { get; set; }

    [Key]
    [Column(Order = 1)]
    public Guid MyClassId { get; set; }

    public int Sequence { get; set; }

    public virtual MyClass MyClass { get; set; }
}

public class MyClass
{
    [Key]
    public Guid Id { get; set; }

    public string Url { get; set; }

    // ...
}

// interface part isn't important, I'm just using the wrapper to
// combine data from different sources to eventually be passed to a Json service
public class EntityWrapper : ISomeInterface
{
    public MyClass_MyClasses Relation { get; set; }

    public string Url { get { return MyClass_MyClasses.MyClass.Url; } }

    // ... some other stuff

    public EntityWrapper() { }
}

问题似乎是.Include(Func&lt;,&gt;)在我做这样的事情时没有被尊重:

using(MyContext context = new MyContext())
{

    IEnumerable<EntityWrapper> wrappedResults =
        from relation in context.MyClass_MyClasses.Include(mm => mm.MyClass)
        orderby  relation.Sequence ascending
        select new EntityWrapper { Relation = relation };

    foreach(EntityWrapper wrapper in wrappedResults)
    {
        // always thrown
        if(wrapper.Relation.MyClass == null)
            throw new WtfException("But I specified .Include?");
    }
}

我一直在解决这个问题,而不是选择EntityWrapper,选择MyClass_MyClasses,然后在我的foreach中只分配一个有效的本地变量= new EntityWrapper { ... }。 p>

我的问题是: 我做错了什么吗?或者这是EF的错误吗?

另外:提前道歉,这是对实际代码的解释,因此有些事情可能不完全相同......如果这不可重复,我会尝试复制更多直接版本的类。< / p>

提前致谢。

2 个答案:

答案 0 :(得分:1)

Include和投影是分离的=一旦使用投影Include未自动使用。试试这个:

var results =
    from relation in context.MyClass_MyClasses.Include(mm => mm.MyClass)
    orderby  relation.Sequence ascending
    select relation;

foreach(EntityWrapper wrapper in results.ToList()
                                        .Select(r => new EntityWrapper { Relation = r }))
{
    // always thrown
    if(wrapper.Relation.MyClass == null)
        throw new WtfException("But I specified .Include?");
}

您也可以尝试使用AsEnumerable代替ToList

答案 1 :(得分:0)

尝试删除virtual关键字。

public virtual MyClass MyClass { get; set; }