我有實體的曲線和點之間的一個一對多的關係,定義如下:如何配置包含一個外鍵複合主鍵(EF流利API)
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; }
}
和:
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; }
}
以我上下文類,我配置鍵和導航性能如下(請注意,點實體具有複合主鍵):
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);
}
別的地方的代碼,我填充數據庫:
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);
}
}
時調用SaveChanges()被調用,則會引發錯誤「而更新條目中出現了一個錯誤。」
如果我將Point_Num定義爲Point實體的主鍵,則所有實體都會更新。看起來問題來自於這個事實:複合主鍵(Point_Num,CurveId)包含一個外鍵(CurveId)
我無法理解這一點,這顯然是我缺少的東西。任何幫助都感激不盡!