I'm working on an application that uses Entity Framework to query a database from a third-party application. The database has a large number of tables and no foreign keys. I've mapped the relevant tables to entities using Entity Framework Fluent API.
namespace App.Entities
{
public class Ticket
{
public int Id { get; set; }
public virtual SalesOrder SalesOrder { get; set; }
public int SalesOrderId { get; set; }
}
public class SalesOrder
{
public int Id { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
public virtual ICollection<Ticket> Lines { get; set; }
}
}
Note that the column and table name mappings are ommitted since I don't think they're relevant.
namespace App.Mappings
{
public class TicketMap : EntityTypeConfiguration<Ticket>
{
public TicketMap() {}
}
public class SalesOrderMap : EntityTypeConfiguration<SalesOrder>
{
public SalesOrderMap()
{
HasMany(t => t.Tickets)
.WithRequired(t => t.SalesOrder)
.HasForeignKey(t => t.SalesOrderId);
HasMany(t => t.Lines)
.WithRequired(t => t.SalesOrder)
.HasForeignKey(t => t.SalesOrderId);
}
}
}
The entities and their mappings are correctly registered with Entity Framework.
I'm receiving the following MetadataException
when I try to run a query:
Schema specified is not valid. Errors: The relationship 'App.SalesOrder_Tickets' was not loaded because the type 'App.Ticket' is not available.
Note that the namespace of Ticket
shown in the above message is wrong. The entity class is actually in App.Entities.Ticket
. However, I don't know if this is related to the problem or not.
The problem was this pair of lines:
public virtual ICollection<Ticket> Tickets { get; set; }
public virtual ICollection<Ticket> Lines { get; set; }
The element type of the second collection was supposed to be different to that of the first:
public virtual ICollection<TicketLine> Lines { get; set; }
Changing this fixed the problem.
I had the same error message and the problem for me was that I had two different edmx models with Entities of the same name. I guess EF couldn't load some of the related entities and was giving a msg.
I solved deleting entities from one model (changing name would work as well I guess) and rebuilding the solution.