I got the exception as soon I call the SubmitChanges()
The ids assigned are valid and already created in the database the "FirstLevelReprotDataSource" is refers to "ReportDataSource" Class All data come from same datacontextGroupingDataMember gdm = new GroupingDataMember();
gdm.DataMemberID = 87;
gdm.FirstLevelDataSourceID = 61;
gdm.CreatedBy = "";
gdm.CreationDate = DateTime.Now;
SelectedReportDataSource.FirstLevelReportDataSource.GroupingDataMembers.Add(gdm);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_GroupingField_ReportDataSource". The conflict occurred in database "HumanResourcesDocumentManagement", table "dbo.ReportDataSource", column 'ID'. The statement has been terminated.
Any suggestions?
[Association(Name="ReportDataSource_GroupingDataMember", Storage="_FirstLevelReportDataSource", ThisKey="FirstLevelDataSourceID", OtherKey="ID", IsForeignKey=true)]
public ReportDataSource FirstLevelReportDataSource
{
get
{
return this._FirstLevelReportDataSource.Entity;
}
set
开发者_如何学C {
ReportDataSource previousValue = this._FirstLevelReportDataSource.Entity;
if (((previousValue != value)
|| (this._FirstLevelReportDataSource.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._FirstLevelReportDataSource.Entity = null;
previousValue.GroupingDataMembers.Remove(this);
}
this._FirstLevelReportDataSource.Entity = value;
if ((value != null))
{
value.GroupingDataMembers.Add(this);
this._FirstLevelDataSourceID = value.ID;
}
else
{
this._FirstLevelDataSourceID = default(int);
}
this.SendPropertyChanged("FirstLevelReportDataSource");
}
}
}
First of all, since you are calling SelectedReportDataSource.FirstLevelReportDataSource.GroupingDataMembers.Add(gdm), you don't need to set gdm.FirstLevelDataSourceID = 61. The .Add takes care of setting the ID.
Secondly, try to avoid setting ID fields by value. It's better to stick with the Foreign Key by saying entity.ForeignKeyProperty = dataContext.ForeignKeyTableObjects.SingleOrDefault(o=>o.ID.Equals(50)); or whatever the ID is. That way you're binding an OBJECT to the entity, not an ID to the entity's field.
Thirdly, make sure that those IDs exist in the db- 87, 61, etc. And check to see if gdm.ReportDataSource is required. If it is, you're not setting it above. That could cause the failure.
Since you're setting the ids explicitly in your example, why not add the object you are creating directly to the context's GroupingDataMember table and then submit changes to your database? In either case, take a look at the SQL generated by LINQ to get a better idea as to what is actually happening on the DB.
-m
精彩评论