实体框架代码优先 - 不能在 LINQ to 实体查询中构造实体或复杂类型
本文关键字:实体 查询 类型 复杂 to LINQ 代码 框架 不能 | 更新日期: 2023-09-27 18:33:30
第一个使用 EF 6 的项目。我有3张桌子,设施,Ewc和FacilityToEwc。每个设施可以有许多Ewc。
public class Facility
{
public int FacilityId { get; set; }
public string FacilityName {get; set;}
}
public class Ewc
{
public int EwcId { get; set; }
public sting EwcCode { get; set;}
}
public class FacilityToEwc
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FacilityToEwcId { get; set; }
public int FacilityId { get; set; }
public Facility Facility { get; set; }
public int EwcId { get; set; }
public Ewc Ewc { get; set; }
}
希望这是正确的。问题是我需要一种方法来为每个设施返回 JSON 格式的所有 EWC 代码。这就是我所做的
public class FacilityDTO
{
public int FacilityId { get; set; }
public IEnumerable<Ewc> Ewc { get; set; }
}
public IEnumerable<FacilityDTO> GetFacilities()
{
var result = (from currentFacility in db.Facilities
select new FacilityDTO()
{
FacilityId = currentFacility.FacilityId,
Ewc = from ewcDetail in db.FacilityToEwcs
where ewcDetail.FacilityId == currentFacility.FacilityId
select new Ewc { EwcCode = ewcDetail.Ewc.EwcCode }
});
return result;
}
当我执行上述方法时,我在此帖子标题中出现错误。感谢帮助。谢谢。
我只需要创建 2 个表,一旦我将映射代码放置在 OnModelCreation 中,EF 就会自动创建映射表。请参阅下面的代码。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Facility>()
.HasMany(x => x.Ewc)
.WithMany(x => x.Facility)
.Map(x =>
{
x.ToTable("FacilityToEwc");
x.MapLeftKey("FacilityId");
x.MapRightKey("EwcId");
});
base.OnModelCreating(modelBuilder);
}
public class Facility
{
public int FacilityId { get; set; }
public string FacilityName {get; set;}
public ICollection<Ewc> Ewc { get; set; }
}
public class Ewc
{
public int EwcId { get; set; }
public sting EwcCode { get; set;}
public ICollection<Facility> Facility { get; set; }
}