I am trying to create a self-referencing org table in Entity Framework v6 code-first - and I can't seem to get it right... (so far I always worked with the EF 4.0 visual designer).
I have this class (that corresponds to a SQL Server table):
[Table("Organisation")]
public partial class Organisation
{
public int OrganisationId { get; set; }
public int? ParentOrgId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[ForeignKey("ParentOrgId")]
public virtual Organisation Parent { get; set; }
}
Pretty standard stuff - and this is my DbContext
derived class which should set up this self-referencing hierarchy:
public partial class HierarchyCtx : DbContext
{
public HierarchyCtx() : base("name=HierarchyCtx")
{
}
public virtual DbSet<Organisation> Organisation { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Organisation>()
.Property(e => e.Name)
.IsUnicode(false);
modelBuilder.Entity<Organisation>()
.HasOptional(e => e.Parent)
.WithMany()
.HasForeignKey(m => m.ParentOrgId)
.WillCascadeOnDelete(false);
}
}
Now I added a few rows to my SQL Server table, but when trying to load these entries, I get an error:
System.Data.SqlClient.SqlException: Invalid column name 'Discriminator'.
Invalid column name 'Discriminator'.
Invalid column name 'Discriminator'.
Invalid column name 'ParentOrganisation_OrganisationId'.
Not entirely sure what's happening here.... what is Discriminator
(a column I do not have) and why do I need it? How to add it? And why is EF trying to find a column ParentOrganisation_OrganisationId
when I set the model up to use ParentOrgId
as foreign key column??
This is a bit of a mystery to me..... anyone out there which has successfully done this in EF code-first before? What am I missing?