كيفية تغيير قيمة المرتبطة المجال
-
10-07-2019 - |
سؤال
لدي 2 الطبقات مع LINQ رابطة بينهما أي:
Table1: Table2:
ID ID
Name Description
ForiegnID
الرابطة هنا هو بين جدول1.ID -> Table2.ForiegnID
أنا بحاجة إلى أن تكون قادرة على تغيير قيمة Table2.ForiegnID, ولكن أنا لا أعتقد أنه بسبب رابطة (كما عند إزالته ، يعمل).
ولذلك لا أحد يعرف كيف يمكن تغيير قيمة حقل المرتبطة بها Table2.ForiegnID?
المحلول
تحقق من المصمم.cs الملف.هذا هو المفتاح الملكية
[Column(Storage="_ParentKey", DbType="Int")]
public System.Nullable<int> ParentKey
{
get
{
return this._ParentKey;
}
set
{
if ((this._ParentKey != value))
{
//This code is added by the association
if (this._Parent.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
//This code is present regardless of association
this.OnParentKeyChanging(value);
this.SendPropertyChanging();
this._ParentKey = value;
this.SendPropertyChanged("ParentKey");
this.OnServiceAddrIDChanged();
}
}
}
وهذه الجمعيات المنشأة.
[Association(Name="Parent_Child", Storage="_Parent", ThisKey="ParentKey", IsForeignKey=true, DeleteRule="CASCADE")]
public Parent Parent
{
get
{
return this._Parent.Entity;
}
set
{
Parent previousValue = this._Parent.Entity;
if (((previousValue != value)
|| (this._Parent.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Parent.Entity = null;
previousValue.Exemptions.Remove(this);
}
this._Parent.Entity = value;
if ((value != null))
{
value.Exemptions.Add(this);
this._ParentKey = value.ParentKey;
}
else
{
this._ParentKey = default(Nullable<int>);
}
this.SendPropertyChanged("Parent");
}
}
}
فمن الأفضل لتعيين التغييرات من خلال جمعية بدلا من المفتاح.بهذه الطريقة, كنت لا داعي للقلق حول ما إذا كان الأصل هو تحميلها.
نصائح أخرى
Table1: Table2:
ID ID
Name Description
ForeignID
مع هذا :
Table2.ForeignID = 2
تتلقى خطأ..........
على سبيل المثال :
يمكنك تغيير ForeignID الحقل في الجدول 2 مثقال ذرة هذا :
Table2 table = dataContext.Table2.single(d => d.ID == Id)
table.Table1 = dataContext.Table1.single(d => d.ID == newId);
حيث متغير newId
هو معرف سجل في الجدول 2 أن تحب المنتسبين مثقال ذرة سجل في الجدول 1
هل تريد أن تقترن مع آخر سجل في جدول1 أو تغيير جدول1.الهوية ؟ إذا كان الخيار 1 ، تحتاج إلى إزالة تلك الجمعيات وتعيين واحدة جديدة.إذا كان الخيار 2 ، تحقق لك db ومعرفة ما إذا كان التحديث تتالي أجل تمكين هذا fk من الحصول على سجل تغيير قيمة معرف.