My project is Database First and I'm using Entity Framework 6.2.0.
So I have following classes in simple illustration:
Person [1] [n] Link_Table [n] [1] Area
====== ========== ====
ID ID ID
PersonID (FK)
AreaID (FK)
Now when using following code it will through me an inner exception of "invalid column name 'Area2_ID'".
Db_Context db = new Db_Context();
// getting all links with specific "personID"
List<Link_Table> links = db.Link_Table.Where(item => item.PersonID == personID).ToList();
// now getting all areas
List<Area> areas= new List<Area>();
foreach (Link_Table link in links)
{
// ERROR
areas.Add(db.Area.Where(item => item.ID == link.areaID).First());
}
I've already read a little bit about this problem by another users and the problem should be in the (auto-generated) OnModelCreating.
modelBuilder.Entity<Area>()
.Property(e => e.Description)
.IsUnicode(false);
modelBuilder.Entity<Area>()
.HasOptional(e => e.Area1)
.WithRequired(e => e.Area2);
For whatever reason using EF in code and creating a new Area-Object, it will show me not only "ID"-Property, but also "Area1"- and "Area2"-Property.
Question How i have to handle it? The columns "Area1_ID" and "Area2_ID" only exist in EF, not in the database. Can I remove these properties or something else to prevent my exception?
EDIT: My models:
[Table("Area")]
public partial class Area
{
public Guid ID { get; set; }
[StringLength(40)]
public string Name { get; set; }
[Column(TypeName = "text")]
public string Description{ get; set; }
public virtual Area Area1 { get; set; }
public virtual Area Area2 { get; set; }
}
public partial class Link_Table
{
public Guid ID { get; set; }
public Guid? Person_ID { get; set; }
public Guid? Area_ID { get; set; }
public virtual Person Person{ get; set; }
}
[Table("Person")]
public partial class Person
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Person()
{
Link_Table = new HashSet<Link_Table>();
}
public Guid ID { get; set; }
}