I’ve created a relationship on the same table, and the relationship is declared in the OnModelCreating. See code below.
When trying to get all items with the following code var allitems = MyContext.WallItems
I get the following error: Server Error in ‘/’ Application.
Unable to cast object of type ‘WallItem’ to type ‘System.Collections.Generic.List`1[WallItem]’.
Have i defined my relationship in a wrong way, or is there a better way?
[Table("WallItems")]
public class WallItem
{
public WallItem() { Id = Guid.NewGuid(); }
/// <summary>
/// Item Id
/// </summary>
[Key]
public Guid Id { get; set; }
/// <summary>
/// Enables replies on wall items. Links to the root item.
/// </summary>
public Guid? ThreadRoot { get; set; }
/// <summary>
/// Collection of replies
/// </summary>
public virtual List<WallItem> Comments { get; set; }
}
public class MyContext : DbContext
{
public DbSet<WallItem> WallItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<WallItem>()
.HasOptional(c => c.Comments)
.WithMany()
.HasForeignKey(c => c.ThreadRoot);
}
}
You have mistake in your Fluent API configuration. This will work: