I'm trying to build relationship while wanted to specify child and parent tables foreign key in addition to navigation property, model looks like this
public class Parent
{
public Parent()
{
this.Childern = new HashSet<Child>();
}
public Guid Id { get; set; }
public string Name { get; set; }
//public Guid Child_Id { get; set; }
public ICollection<Child> Childern { get; set; }
}
public class Child
{
public Child()
{
this.Parent = new Parent();
}
public Guid Id { get; set; }
public string Name { get; set; }
public Guid Parent_Id { get; set; }
public Parent Parent { get; set; }
}
With only above model when i build and run project, i get expected results on navigation properties as navigation properties are populated with expected data. But i get additional un-wanted column in database as below
Id Name Parent_Id Parent_Id1 (FK)
I further configured relationship in OnModelCreating like below
modelBuilder.Entity<Child>()
.HasRequired(p => p.Parent)
.WithMany(p => p.Childern)
.HasForeignKey(k => k.Parent_Id);
This time I got desired result on table structure now table looks like this
Id Name Parent_Id (FK)
But I'm getting null on navigation properties, please note that I'm trying Eagerly Loading
public static void TestParent()
{
using (var context = new ILDBContext())
{
var parents = context.Parents
.Include(p => p.Childern)
.ToList();
foreach (var parent in parents)
{
Console.WriteLine("Parent: {0} Childern: {1}", parent.Name, parent.Childern.Count());
foreach (var child in parent.Childern)
{
Console.WriteLine("Child: {0}", child.Name);
}
}
}
}
In addition I will be thankful if anyone can advise how should i configure relationship if i need FK in both models like, Parent_Id and Child_Id Thanks.