我有一个来自三个相关数据表的LINQ查询,我需要在MVC应用程序的视图页面中显示它们。
AllFacility和Address以及AllFacility和AllPractitionerlocation之间存在一对多的关系。
然而,当我运行应用程序时,我得到:
Unable to cast object of type
'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1
[<>f__AnonymousType4`2[<>f__AnonymousType3`2
[PODSModel.Models.ODS.AllFacility,PODSModel.Models.ODS.Address]
,PODSModel.Models.ODS.AllPractitionerLocation]]' to type
'System.Linq.IQueryable`1[PODSModel.Models.ODS.AllFacility]以下是我的代码中的实际查询:
public IQueryable<AllFacility> getFacility(
int SRCFacilityID,
ProviderUpdateType providerUpdateType = ProviderUpdateType.FOF)
{
var facility = _ODSContext.AllFacilities
.Where(f => f.SRCFacilityID == SRCFacilityID)
.Join(
_ODSContext.Addresses,
oks => oks.AddressID,
iks => iks.AddressID,
(oks, iks) => new {allfacility = oks, iks })
.Join(
_ODSContext.AllPractitionerLocations,
oks1 => oks1.allfacility.AllFacilityID,
iks1 => iks1.AllFacilityID,
(oks1, iks1) => new { oks1, iks1 })
.AsQueryable();
return (IQueryable<AllFacility>)facility;
}更新: Svyatoslav给我的答案修复了这个错误,但还有更多错误。当我按照他的建议对代码建模时,我只能从第一个表中挑选列,因为这是它唯一接受的模型作为新参数。
.Select( k => new AllFacility)
{
...
}因此,我创建了一个新模型,其中包含三个连接表(.Include...)中我想要的列。但是,当我这样做的时候,EF抛出了一个关于无效列AllFacilityID1的错误。我认为这是因为第三个表在AllFacilityID上有一个指向第一个表的外键,EF将其重命名为一些原因。
任何关于如何解决这个问题的想法。我根本不需要在最终结果中使用这个字段(我不这么认为)。
谢谢,
发布于 2021-10-20 08:00:10
在这里,我将使用一种不同的方法,并使用ForeignKey - InverseProperty而不是显式地使用连接。这是EF给你的一个很棒的工具,为了让生活更简单,代码更易读,不使用它是一种遗憾。
[Table("AllFacility")]
public class AllFacility
{
...
public AllFacility()
{
this.Addresses = new HashSet<Address>();
this.AllPractitionerlocations = new HashSet<AllPractitionerlocation>();
}
public long addressID { get; set; }
public long allPractitionerlocationID{ get; set; }
[InverseProperty("AllFacility")]
public virtual Address Addresses { get; set; }
[InverseProperty("AllFacility")]
public virtual AllPractitionerlocation AllPractitionerlocations { get; set; }
}
[Table("AllPractitionerlocation")]
public class AllPractitionerlocation
{
...
public long allFacilityID { get; set; }
[ForeignKey("allFacilityID")]
public virtual AllFacility AllFacility { get; set; }
}
[Table("Address")]
public class Address
{
...
public long allFacilityID { get; set; }
[ForeignKey("allFacilityID")]
public virtual AllFacility AllFacility { get; set; }
}然后,您可以在没有显式联接的情况下访问实体,并且联接在幕后进行。然后,您可以执行以下操作:
_ODSContext.Addresses
.Where(x => x.AllFacility.SRCFacilityID == SRCFacilityID)
.Select(x => x.AllFacility.AllPractitionerlocations
.Select(y => new someDto
{
Property1 = x.AllFacility.someField1,
Property2 = x.someField2,
Property3 = y.someField3,
})https://stackoverflow.com/questions/69634561
复制相似问题