EF查询使用List集合遇‘edm type is ambiguous’错误的解决咨询
解决EF查询中“edm type is ambiguous”错误的调整方案
核心问题原因
你遇到的错误是因为在EF的LINQ to Entities查询中,直接关联了内存中的EF实体类型集合(CustomerGroupSubscriptions),EF无法区分内存实体和数据库映射的EDM实体类型,导致类型歧义。同时第二个查询存在语法错误(toList()应为ToList())。
具体调整步骤
改用匿名类存储内存集合数据
修改第一个查询,用匿名类替代EF实体类型CustomerGroupSubscriptions,避免EF将内存对象识别为EDM模型的一部分:var customercurrentGroupSubscriptions = customergroupSubscriptions.GroupBy(r => r.GroupId) .Select(g => g.OrderByDescending(r => r.EndDate.Value).FirstOrDefault()) .Select(i => new { SubscriptionId = i.SubscriptionId, GroupId = i.GroupId, EndDate = i.EndDate }).ToList();或使用独立DTO类(推荐)
如果需要复用内存集合的结构,创建一个非EF实体的DTO类(不要在DbContext中注册为DbSet,也不要添加EF映射属性):public class CustomerGroupSubscriptionDto { public int SubscriptionId { get; set; } public int GroupId { get; set; } public DateTime? EndDate { get; set; } }然后修改第一个查询的投影:
.Select(i => new CustomerGroupSubscriptionDto { SubscriptionId = i.SubscriptionId, GroupId = i.GroupId, EndDate = i.EndDate }).ToList();修正语法错误
第二个查询中的toList()是小写,不符合C#语法,必须改为ToList():var SubscriptionsForGroupSubscription = (from s in db.Subscriptions join i in customercurrentGroupSubscriptions on s.SubscriptionId equals i.SubscriptionId select new IndividualGroupSubscription { OriginalSubscriptionId = s.OriginalSubscriptionId } ).ToList();
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

