I am using Linq To Sql to insert few data to a table in Sql server 2008.
memadd.add_id = Convert.ToDecimal(resadd);
memadd.mem_add = txtResAdd.Text;
memadd.tel_no1 =Convert.ToDecimal(txtResTelNo.Text);
memadd.mob_no1 = Convert.ToDecimal(txtResMobNo.Text);
memadd.state = drpResState.Text;
memadd.city = drpResCity.Text;
memadd.pin_no = Convert.ToDecimal(txtResPinNo.Text);
dt.mem_addresses.InsertOnSubmit(memadd);
dt.SubmitChanges();
My issue here is that when i insert data into the field , it gives me an error saying
Can't perform Create, Update or Delete operations on 'Table(mem_address)' because it has no primary key.
I have a situation wherein i cant set primary key to that table .Can anyone please point me out what needs to be done here.
Thanks
Just tell the memadd table in the DBML designer to select add_id as a PK for example.
It needs not be on the database itself.
Linq to sql can't be used in such situations. Just warp your insert statement into a stored procedure and add the procedure to your data model. If you can't do that, write a normal function with a bit of in-line SQL
Linq does not support table w/o primary keys...
Related
I am facing an issue I hope to get it solved by here. I have 3 different tables in a DataSet and I want to insert it in the database table.
I know I can do this using SqlBulkCopy but there is a catch and that is I want to check if the data already exists in the database then I want it to get updated instead of insert.
And if the data doesn't exist in the database table, I want to insert it then. Any help on this would be appreciated.
I know I can iterate it through each record and then fire a procedure which will check for its existence if it exists den update or else insert. But the data size is huge and iterating through each record would be a time taking process, I don't want to use this approach.
Regards
Disclaimer: I'm the owner of the project Bulk Operations
This project allows to BulkInsert, BulkUpdate, BulkDelete, and BulkMerge (Upsert).
Under the hood, it does almost what #marc_s have suggested (Use SqlBulkCopy into a temporary table and perform a merge statement to insert or update depending on the primary key).
var bulk = new BulkOperation(connection);
bulk.BulkMerge(dt);
I am trying to delete a record from Database but for a specific row m not able to do it.
This is my Linq Query to delete it
FormSubmit formSubmit = db.FormSubmits.Find(id);
db.FormSubmits.Remove(formSubmit);
db.SaveChanges();
And i am getting an Error Like this
I know this is Because of Foreign Key but how to Solve it.In SQL We use NO CHECK but not getting in linq Query.
Not an expert on this, but this seems the solution in your case:
Specify the UpdateCheck = UpdateCheck.Never on your column in your entity. This will disable the update check and will most likely fix your issue.
Another option is to set cascade deletion on the table in the database.
I'm stuck on a little problem concerning database.
Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.
I have no trouble inserting the information in the database;
var cmd = new SqlCommand("insert into [customer_info]
(customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();
Now, I would like to update my table or just fill it with new information. How can I achieve this?
I've tried using TableAdapter but it does not work.
And I'm only permitted to add one XML because I can only have one customer_nr as primary key.
So basically how do I update or fill my table with new information?
Thanks.
One way would be to bulk insert the data into a new staging table in the database (you could use SqlBulkCopy for this for optimal insert speed). Once it's in there, you could then index the customer_nr field and then run 2 statements:
-- UPDATE existing customers
UPDATE ci
SET ci.firstname = s.firstname,
ci.lastname = s.lastname,
... etc
FROM StagingTable s
INNER JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
-- INSERT new customers
INSERT Customer_Info (customer_nr, firstname, lastname, ....)
SELECT s.customer_nr, s.firstname, s.lastname, ....
FROM StagingTable s
LEFT JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
WHERE ci.customer_nr IS NULL
Finally, drop your staging table.
Alternatively, instead of the 2 statements, you could just use the MERGE statement if you are using SQL Server 2008 or later, which allows you to do INSERTs and UPDATEs via a single statement.
If I understand your question correctly - if the customer already exists you want to update their information, and if they don't already exist you want to insert a new row.
I have a lot of problems with hard-coded SQL commands in your code, so I would firstly be very tempted to refactor what you have done. However, to achieve what you want, you will need to execute a SELECT on the primary key, if it returns any results you should execute an UPDATE else you should execute an INSERT.
It would be best to do this in something like a Stored Procedure - you can pass the information to the stored procedure at then it can make a decision on whether to UPDATE or INSERT - this would also reduce the overhead of making several calls for your code to the database (A stored procedure would be much quicker)
AdaTheDev has indeed given the good suggestion.
But in case, you must insert/update from .NET code then you can
Create a stored procedure that will handle insert/update i.e. instead of using a direct insert query as command text, you make a call to stored proc. The SP will check if row exists or not and then update (or insert).
User TableAdapter - but this would be tedious. First you have to setup both insert & update commands. Then you have to query the database to get the existing customer numbers and then update the corresponding rows in the datatable making the Rowstate as Updated. I would rather not go this way.
I'm using Oracle provider for Entity framework (beta), and I'm facing a problem.
Our tables have Id columns, which are set to be Identity in StoreGeneratedPattern. I thought that EF will automatically do "underlying works", such as create sequences, and get new identity for each record I add to the table. But when I run code to add a new record, such as:
var comment = new Comment
{
ComplaintId = _currentComplaintId,
Content = CommentContent.Text,
CreatedBy = CurrentUser.UserID,
CreatedDate = DateTime.Now
};
context.Comments.AddObject(comment);
context.SaveChanges();
an Exception still throws, which is
{"ORA-00001: unique constraint (ADMINMGR.CONSTRAINT_COMMENT)
violated"}
(CONSTRAINT_COMMENT is the constrain requires that comment identity
must be unique.
How do I solve this?
Thank you very much!
StoreGeneratedPattern="Identity" simply tells EF that the value will be generated DB-side on insert, and that it shouldn't supply a value in insert statements.
You still need to create a sequence in Oracle:
create sequence ComplaintIdSequence minvalue 1 maxvalue 9999999 start with 1 increment by 1;
and a trigger to make table inserts use it:
create or replace trigger CommplaintIdTrigger
before insert on comment for each row
begin
if :new.ComplaintId is null then select ComplaintIdSequence.nextval into :new.ComplaintId from dual;
endif;
end;
Oracle 12c has resolved it
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SomeNumber { get; set; }
Another option would be:
Create a sequence the way Alextansc described.
Create a stored procedure that uses MySequence.nextval as it's primary key.
Map 'insert' for this model to your stored procedure and it works!
I've tested this using database first approach.
Using database first mapping to a stored procedure is pretty simple. Go to your edmx file and right click the model you want to map to a stored procedure. Click "stored procedure mappings." The dialog at the bottom of the page gives you three drop down menus for mapping insert, update, and delete to stored procedures.
I am using Oracle ODP.NET, Managed driver and Entity Framework 6. I created my tables using the code-first approach but wasn't able to add any records due to a null primary key.
The solution was to grant my user both:
'CREATE SEQUENCE' and
'CREATE TRIGGER'
permissions and re-create the schema.
I realized this after using the -verbose flag in the package management console
Instead of remember all of this SQL, you could easily do by using Mig# like this:
var schema = new DbSchema(ConnectionString, DbPlatform.Oracle12c);
schema.Alter(db => db.CreateTable("TableName")
.WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
...);
In this example, the Id column will have the required trigger and sequence generated by Mig# automatically.
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: 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