I am brand new to C# and Entity Framework. I have been used these tutorials and StackOverflow to give me a better understanding.
- http://developer.telerik.com/featured/working-with-databases-through-visual-studio/
- https://msdn.microsoft.com/en-us/data/jj193542
Using the Code-First approach, I have created a parent table and inserted data into the table no problem. When I had the parent table working correctly, I added the child table. I am now trying to insert data into that child table. However, I always get a stack overflow error. I think that there is something wrong with my mapping, but I am not sure what.
The following is my code. This is where I define the database context and the objects for the database.
public class DatabseContext : System.Data.Entity.DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
}
public class Parent
{
private Guid parentIdVal;
public Parent()
{
Children = new List<child>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid parentId
{
get { return parentIdVal; }
set { parentIdVal = Guid.NewGuid(); }
}
[Required]
[StringLength(4)]
public string parentData { get; set; }
public virtual List<Child> Children { get; set; }
}
public class Child
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid childId
{
get { return childId; }
set { childId = Guid.NewGuid(); }
}
[ForeignKey("Parent")]
public Guid parentId { get; set; }
[Required]
[StringLength(65)]
public string childData { get; set; }
public virtual Parent Parent { get; set; }
}
I have a different class what parses a file and inserts rows into each table. This is the code:
private static void addParentRecord(String source)
{
using (var db = new DatabaseContext())
{
Parent parent = new Parent();
addDataToParent(parent);
createChildren(source, parent);
db.Parents.Add(parent);
db.SaveChanges();
}
}
private static void createChildren(String source, Parent parent)
{
Regex regex = new Regex(pattern);
foreach (Match match in regex.Matches(source))
{
Child child = new child();
child.childData = match.Groups[group].Value;
parent.Children.Add(child);
}
}
So the code creates both the parent and the child tables. It creates both the parent and the child objects and populates the objects. When I go to save the database changes, however, it continually calls the get ChildId and I get a stack overflow. There is some loop somewhere. I think it is because I don't have the parent-child mapping set up correctly.
Any help, pointers or links would be greatly appreciated. Thank you.