简体   繁体   中英

Entity Framework Code First - The entity or complex type cannot be constructed in a LINQ to Entities query

first project using EF 6. I have 3 tables, Facility, Ewc and FacilityToEwc. Each facility can have many Ewc's.

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; }
}

Hope this is correct. The problem is that I need one method to return for each facility all EWC codes in JSON format. This is what I have done

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;
}

When I execute the above method I get the error in this posts title. Help appreciated. Thanks.

I had to just create 2 tables and EF auto created the mapping table once I placed the mappingcode in OnModelCreating. See code working below.

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; }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM