LINQ update on table having no primary key


I was trying to update a record in a table last night, using LINQ. Everything was fine and running without any errors.
Surpisingly the record was not getting updated. I then attached the modified object to the context. It started giving an exception as,

Can't perform Create, Update or Delete operations on Table because it has no primary key.

Then I realised that there is no primary key assigned to the table. The possible solution was to change the database schema and add primary key 
to that table. But this change was not acceptable.
Further debugging into the code I got the workaround for this. 

When we generate a class file using a tool such as sqlmetal or anything else, certain attributes are associated with the columns of that table.
We can open that class file and manually add IsPrimary= true attribute to any one of the columns.

This will fool the LINQ engine and treat the respective column as a primary key.

Here is an example for the same.
I have generated a class with table as TableWithNoPK. It has 3 columns as Field1, Field2, Field3.
I assigned IsPrimary attribute to field1 as,

[global::System.Data.Linq.Mapping.ColumnAttribute(Name="field1", Storage="_Field1", DbType="VarChar(50)", IsPrimaryKey= true)]
        public string Field1
        {
            get
            {
                return this._Field1;
            }
            set
            {
                if ((this._Field1 != value))
                {
                    this._Field1 = value;
                }
            }
        }


The c# code goes normal as,

var qry = from NoPK in instance.TableWithNoPK
                      select NoPK;

       TableWithNoPK test = qry.FirstOrDefault();
       test.Field3 = "Gud 1";
       instance.SubmitChanges();


No comments:

Post a Comment