实体框架7导航属性为空
我正在创建实体框架7项目来替换实体框架6项目。实体框架7导航属性为空
我有一个项目实体属于一个国家。然后我有一个linq查询,按国家计数。这是查询。
var results = allItems
.GroupBy(g => g.Country)
.ToDictionary(s => s.Key, s => s.Count());
这适用于EF6,但与EF 7引发异常(例外是在底部)。
这是我的实体:
public class Item
{
[Key]
public int id { get; set; }
[Required]
public int Countryid { get; set; }
[ForeignKey("Countryid")]
public virtual Country Country { get; set; }
}
在EF 7,使用调试器我看到国家为空(这是导航属性),但我确实有countryid。在EF 6中,我有一个导航属性的对象。另外,我使用Moq进行单元测试,他们工作(显示nav属性)。
我试图添加一个包含,但我不应该需要。我不需要EF 6或Mock。
使用包括给出了这样的:
var results = allItems
.Include(i => i.Country)
.GroupBy(g => g.Country)
.ToDictionary(s => s.Key, s => s.Count());
我得到同样的错误。
以下是错误:
Expression of type 'System.Func
2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier
2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier2[FMS.DAL.Entities.ActionItem,Microsoft.Data.Entity.Storage.ValueBuffer],Microsoft.Data.Entity.Storage.ValueBuffer],FMS.DAL.Entities.MemberCountry]' cannot be used for parameter of type 'System.Func
2[FMS.DAL.Entities.ActionItem,FMS.DAL.Entities.MemberCountry]' of method 'System.Collections.Generic.IEnumerable1[System.Linq.IGrouping
2[FMS.DAL.Entities.MemberCountry,FMS.DAL.Entities.ActionItem]] _GroupBy[ActionItem,MemberCountry,ActionItem](System.Collections.Generic.IEnumerable1[FMS.DAL.Entities.ActionItem], System.Func
2[FMS.DAL.Entities.ActionItem,FMS.DAL.Entities.MemberCountry], System.Func`2[FMS.DAL.Entities.ActionItem,FMS.DAL.Entities.ActionItem])'
目前的GroupBy不EF7实现的功能的状态可以在道路地图页面上在这里找到。 https://github.com/aspnet/EntityFramework/wiki/Roadmap
一个解决将是:
context.Countries.Select(x => new
{
x.Id,
Items = x.Items.Count
}).ToDictionary(x => x.Id, x => x.Items);
public class Country
{
public int Id { get; set; }
//Add this property
public virtual ICollection<Item> Items { get; set; }
}
//Generated SQL
SELECT (
SELECT COUNT(*)
FROM [Item] AS [i]
WHERE [x].[Id] = [i].[Countryid]
), [x].[Id]
FROM [Country] AS [x]
这将需要新增一个项目属性,以国家,但将让你实现你是什么毕竟Linq中。你可能会去写在SQL查询和EF执行,但可能不是最好的选择。