Cómo cambiar el valor del campo asociado
-
10-07-2019 - |
Pregunta
Tengo 2 clases con una asociación LINQ entre ellas, es decir:
Table1: Table2:
ID ID
Name Description
ForiegnID
La asociación aquí es entre Table1.ID - > Table2.ForiegnID
Necesito poder cambiar el valor de Table2.ForiegnID, sin embargo, no puedo y creo que es debido a la asociación (como cuando lo elimino, funciona).
Por lo tanto, ¿alguien sabe cómo puedo cambiar el valor del campo asociado Table2.ForiegnID?
Solución
Consulte el archivo designer.cs. Esta es la propiedad de la clave
[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();
}
}
}
Y esta es la propiedad de las asociaciones.
[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");
}
}
}
Es mejor asignar cambios a través de la asociación en lugar de la clave. De esa manera, no tiene que preocuparse por si el padre está cargado.
Otros consejos
Table1: Table2:
ID ID
Name Description
ForeignID
Con esto:
Table2.ForeignID = 2
recibes un error ..........
Ejemplo:
Puede cambiar el campo ForeignID en la Tabla 2 con esto:
Table2 table = dataContext.Table2.single(d => d.ID == Id)
table.Table1 = dataContext.Table1.single(d => d.ID == newId);
Donde la variable newId
es la identificación del registro en la Tabla 2 que le gustaría asociar con el registro en la Tabla 1
¿Desea asociar con otro registro en table1 o cambiar table1.id? si es la opción 1, debe eliminar esa asociación y establecer una nueva. Si es la opción 2, verifique su base de datos y vea si la cascada de actualización sí está habilitada para este fk y luego obtenga el registro y cambie el valor de id.