Setting Foreign keys in Linq to SQL

后端 未结 3 1436
花落未央
花落未央 2021-01-02 09:52

It\'s well known that you cannot set foreign key IDs directly in Linq to SQL if the entities have already been loaded. You can however look up the entity by it\'s foreign k

3条回答
  •  粉色の甜心
    2021-01-02 10:00

    Normally the setter of AppointmentStatusId looks like: (Code in C# but it should be easy to get it)

    [Column(Storage="_AppointmentStatusId", DbType="Int")]
    public System.Nullable AppointmentStatusId
    {
        get
        {
            return this._AppointmentStatusId;
        }
        set
        {
            if ((this._AppointmentStatusId != value))
            {
                if (this._AppointmentStatus.HasLoadedOrAssignedValue)
                {
                    throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
                }
                this.OnCapabilityIdChanging(value);
                this.SendPropertyChanging();
                this._AppointmentStatusId = value;
                this.SendPropertyChanged("AppointmentStatusId");
                this.OnCapabilityIdChanged();
            }
        }
    }
    

    So, if I were you, I'd add a method SetAppointmentStatusId(int statusId) to the partial file that comes with the designer generated one, and add more whenever needed for other properties. You may even choose to make the setter of the property private (from the designer select the property and press F4 to for the VS properties window to change accessibility).
    In this method I'd write code identical to the setter except that it does NOT include this part:

                if (this._AppointmentStatus.HasLoadedOrAssignedValue)
                {
                    throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
                }
    

提交回复
热议问题