I have a one-to-many relationship between entities Curve and Point, defined as follows:
public class Curve
{
public Curve()
{
Points = new HashSet<Point>();
}
public int CurveId { get; set; }
public string Name { get; set; }
public virtual ICollection<Point> Points { get; set; }
}
And:
public class Point
{
public int Point_Num { get; set; }
public int CurveId { get; set; }
public double XCoord { get; set; }
public double YCoord { get; set; }
public virtual Curve Curve { get; set; }
}
In my context class, I configure the keys and navigation properties as follows (note that the Point entity has a composite primary key):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Curve>()
.HasKey(c => c.CurveId);
modelBuilder.Entity<Point>()
.HasKey(p => new { p.Point_Num, p.CurveId });
modelBuilder.Entity<Point>()
.HasRequired(p => p.Curve)
.WithMany(c => c.Points)
.HasForeignKey(p => p.CurveId);
}
Somewhere else in the code, I populate the database:
var curve = new Curve
{
Name = "curve 1"
};
var points = new List<Point>();
points.Add(new Point
{
XCoord = 1d,
YCoord = 1d,
});
points.Add(new Point
{
XCoord = 2d,
YCoord = 2d,
});
foreach (var point in points)
{
curve.Points.Add(point);
}
using (var dbCtxt = new MyDbContext())
{
try
{
dbCtxt.Curves.Add(curve);
dbCtxt.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
An error is thrown when SaveChanges() is called "An error occurred while updating the entries."
If I define Point_Num as the primary key of Point entity, all the entities update just fine. It seems like the problem comes from the fact that the composite primary key (Point_Num, CurveId) contains a foreign key (CurveId)
I cannot get my head around this, there is clearly something I am missing. Any help will be much appreciated!