LINQ to SQL "The INSERT statement conflicted with the FOREIGN KEY constraint " FK_Child_Parent " "



我在尝试使用导航属性将数据插入表中时得到了 SqlException。似乎外键没有自动更新,默认值为 0。同时,它适用于自动生成的类。我不想使用自动生成的模型。

我必须如何修改我的模型才能使其工作?是关于 INotifyPropertyChange 还是 INotifyPropertyChanged?

谢谢。

class Program
{
    static void Main(string[] args)
    {
        var db = new DbContext();
        var p = db.Parents.Single(x => x.Id == 2);
        p.Children.Add(new Child_ { Name = "P2_Child_1" });
        db.SubmitChanges();
    }
}

class DbContext : DataContext
{
    public DbContext() : base(@"Data Source=.SQLEXPRESS;Initial Catalog=TestDb;Integrated Security=True;") { }
    public Table<Parent_> Parents { get { return GetTable<Parent_>(); } }
    public Table<Child_> Children { get { return GetTable<Child_>(); } }
}
[Table(Name = "Parents")]
class Parent_
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int Id { get; set; }
    [Column]
    public string Name { get; set; }
    [Association(OtherKey = "ParentId")]
    public EntitySet<Child_> Children { get; set; }
}
[Table(Name = "Children")]
class Child_
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int Id { get; set; }
    [Column]
    public int ParentId { get; set; }
    [Column]
    public string Name { get; set; }
    [Association(IsForeignKey = true, ThisKey = "ParentId", OtherKey = "Id")]
    public Parent_ Parent { get; set ; }
}

为了解决这个问题,我不得不在继承的DataContext上手动编写Insert方法:

Public Class ClientDataContext : Inherits DataContext
...
Public Sub InsertYourEntity(instance As YourEntity)
    With instance
        ExecuteDynamicInsert(instance)
        If TypeOf instance Is YourEntity then
            For each child As YourChildEntity In instance.YourChildEntities
                child.YourForeignKeyId = .Id
            Next
        End If
    End With
End Sub

LinqToSql 似乎通过反射使用此方法。因此,一旦编码的锐化器认为它没有使用,但集成测试击中了它。

最新更新