在查询中包含子表时,仅支持初始化程序,实体成员和实体导航属性

时间:2014-09-18 12:42:30

标签: entity-framework linq-to-entities

我有一个由EF 6.1定义的简单的一对多数据库关系。生成的数据库显示正确并具有适当的显式关系。但是,当我尝试涉及子表的查询时,我得到一个NotSupportedException(请参阅post的标题)。失败的代码在GetContractList中(见下文)。

我做了一些挖掘,发现有些人遇到了这个问题,但这些问题似乎与尝试在查询中包含非实体项目有关;我不认为这就是这里发生的事情。

任何人都能看到我做错了什么?

[Table("Contract")]
public class Contract : IContract
{
    [Key,
        DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ContractId { get; set; }
    [StringLength(1023),
        Required]
    public string Name { get; set; }
    public DateTime DateBegin { get; set; }
    public DateTime DateEnd { get; set; }
    public string PhoneNumber { get; set; }
    public virtual ICollection<IMarket> Markets { get; set; }

    public Contract()
    {
        Markets = new List<IMarket>();
}    
}    

[Table("Market")]
public class Market : IMarket
{
    [Key, Column(Order = 0)]
    public int ContractId { get; set; }
    [Key, Column(Order = 1)]
    public int MarketId { get; set; }
}


public IEnumerable<IIdName> GetContractList(IAffiliateContractSearchCriteria criteria)
{
var now = DateTime.UtcNow;

// This is the line throwing the exception.
return _repository.AsQueryable().Where(c => (criteria.IncludeOnlyActive
    ? c.DateBegin < now
    && (c.DateEnd > now || c.DateEnd <= SqlDateTime.MinValue.Value)
    : true)
    && (c.Markets.Any()
    ? c.Markets.Select(m => m.MarketId).Any(x => criteria.MarketIds.Contains(x))
    : true)).OrderBy(a => a.Name).Select(a => new IdName() { Id = a.AffiliateContractId, Name = a.Name });
}

public class ContractSearchCriteria : IContractSearchCriteria
{
    public bool IncludeOnlyActive { get; set; }
    public List<int> MarketIds { get; set; }

    public ContractSearchCriteria()
    {
        IncludeOnlyActive = false;
        MarketIds = new List<int>();
    }

    public ContractSearchCriteria(bool includeOnlyActive, int[] marketIds)
        : this()
    {
        IncludeOnlyActive = includeOnlyActive;
        MarketIds.AddRange(marketIds);
    }

}

1 个答案:

答案 0 :(得分:1)

好的,问题是在定义EF Entity对象和关系时不能使用接口。

我的坏。