开发者

LINQ to SQL : How to Insert record into a view?

I'm using Linq to SQL for the Database operations, and am trying to perform insert operations in a VIEW, It throws the Error,

XXt threw exception开发者_如何学C:  System.InvalidOperationException: Can't perform Create, 
Update or Delete operations on 'Table(XXX)' because it has no primary key.

How to use LINQ to insert a record into View using C#?

Thanks.


You can insert/update into views as per Updatable Views here. Only one underlying table can be inserted/updated to or it will fail. To implement this functionality using LINQ, do the following;

  • In your .DBML file tag one (or more) of the columns in the view as a Primary Key
  • Ensure any mappings in the view you are expecting to insert/update are exposed simply as a link to the base table column. Example;
    • Insertable/Updatable columns cannot include;
      • SUM(BaseTable.ColumnName) as ColumnName
      • ISNULL(BaseTable.ColumName,0) as ColumnName
      • BaseTable.ColumnName1 + ' ' + BaseTable.ColumnName2 as ColumnName
    • But can include;
      • BaseTable.ColumnName
      • BaseTable.ColumnName as MyNewName
  • Tag any of the columns that are not direct mappings to the base table as Auto Generated Value in your .DBML.

Give it a shot. I am successfully using this technique to use views as the only objects i use for both reading/inserting/updating records.


Actually you can insert into a view..if the underlying view has one table then you can insert into it.

If it has more than one table..then u can use instead of triggers;

Also I have inserted a record into a view..in linq to sql. (i have just started learning linq myself).

I had to create a primary key on a view. using the designer and then set the auto sync for that field to never. that should do the trick..


We can do insert, update and delete operations using a VIEW in LINQ to SQL process. All that we need to ensure is: view should have primary key.

We can set primarykey for a field in the view.

open the .dbml file designer and select the field which you want to make as primarykey and press F4 (open properties window).

select true for Primary Key property of the selected field.

Now execute your program. It should work.


You cannot insert into a VIEW. You can only insert into a table.

You can do this - see below.


Auto-Sync must be 'OnInsert' for this field in dbml.


I assume you mean that instead of trying to insert a row into a View, you are trying to insert a row into a table. You do not insert rows into Views.

Having said that, L2S requires your tables to have primary keys, as the error message indicates. Once you create a primary key, and update your .DBML accordingly, you should be fine.

Randy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜