Not able to Delete a Entries from Database in mvc4 - c#

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.

Related

Delete Rows from a Constrained Reference Table

I am trying to delete an object from a table (NewClubProspect) that has reference rows in a table called NewClubProspectNewClubEmail
The error I am getting is
The DELETE statement conflicted with the
REFERENCE constrain
"FK_dbo.NewClubProspectNewClubEmail_dbo.NewClubProspect_NewClubProspect_Id"
The conflict occurred in database
"Reporting", table "dbo.NewClubProspectNewClubEmail", column 'NewClubProspect_Id'.
The statement has been terminated.
The reference table looks like this:
I can solve the problem this way but would rather not use straight SQL. I have removed the try/catches for brevity:
//Delete out of the reference table first
var sql = "delete from NewClubProspectNewClubEmail where NewClubProspect_Id = #p0";
var r = ReportingDBTasks.Query(sql,prospect.Id);
//Delete the parent object
db.NewClubProspects.Remove(prospect);
db.SaveChanges();
How can I delete from the reference table using EF instead of straight SQL?
Thanks
The simplest way would be to enable cascading deletes on the constraint. But I suppose cascades were turned off for a reason, so I'm pretty sure you still have to do this the old fashioned way and delete each one.
Assuming you have a navigation property, it should be something like:
foreach(var nce in prospect.NewClubEmails)
db.NewClubProspectNewClubEmails.Remove(nce);
db.NewClubProspects.Remove(prospect);
db.SaveChanges();

How to remove entity from local copy without removing from Linq DB

I have a problem in Linq. I am getting all the contents a in table when I query. But I don't want to load certain rows which are marked with some special key Y.
So, for this, I'm iterating and removing from my local copy those which are having special key Y.
Later on, when I submit changes, I get an error:
"An attempt was made to remove a relationship between a priceTable and a dataTable. However, one of the relationship's foreign keys (P.Id) cannot be set to null."
Why is it so? How can I alter the contents of a particular entity set without touching some of the rows?
I want the rows that are marked as Y not to be returned from the DB. I don't want use them in my c# at runtime.
Dennis is correct. If you don't required those records marked as 'Y', then use the where clause and exclude those records. Then you are free to modify and update the records back to the database without any issues.
sample where clause looks like below
var data = from p in context.Persons
where p.Required == "Y"
select p;

Linq To Sql Insert Issue

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...

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: 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

Inserting Rows in Relationship using a Strongly Typed DataSet

I'm using ADO.NET with a strongly typed dataset in C# (.NET 3.5). I want to insert a new row to two tables which are related in an 1:n relation.
The table Attachments holds the primary key part of the relation and the table LicenseAttachments holds the foreign key part.
AttachmentsDataSet.InvoiceRow invoice; // Set to a valid row, also referenced in InvoiceAttachments
AttachmentsDataSet.AttachmentsRow attachment;
attachment = attachmentsDataSet.Attachments.AddAttachmentsRow("Name", "Description");
attachmentsDataSet.InvoiceAttachments.AddInvoiceAttachmentsRow(invoice, attachment);
Of course when I first update the InvoicesAttachments table, I'll get a foreign key violation from the SQL server, so I tried updating the Attachments table first, which will create the rows, but will remove the attachment association in the InvoiceAttachments table. Why?
How do I solve this problem?
On the relation between the tables, ensure that the "Both Relation and Foreign Key Constraint" is selected and "Update Rule" is set to "Cascade". Combined with the "Refresh the data table" option on the adapter, after you insert your parent row, the updated ID will "Cascade" down the relationships, preventing foreign key violations in your dataset. Your child tables will then be ready to properly insert into the database.
Some things to try:
When you configure the tableadapter, did you click on advanced options, and check on "refresh data table" so that it will retrieve the identity column value?
For me sometimes I either forgot to check it, or it didn't save the configuration correctly because I didn't have my table identity increment/seed set for whatever reason. Are you using identity increment on the table?
You might also consider just re-creating the adapters for those two tables.
Usually when I go back over everything I find it was something stupid on my part.
Lastly, you might consider calling update on the Primary table, then manually grab the primary key value and manually set the value when you insert the child record. If that doesn't make sense let me know and I will post code.
You need to tell your parent table's table-adapter to refresh the
data-table after update operation.
This is how you can do that.
Open the properties of ProgramUserGroupTableAdapter -> Default Select Query -> Advnaced options. and Check the option of Refresh the data table. Save the adapter now. Now when you call update on table-adapter, the data-table will be updated [refreshed] after the update operation and will reflect the latest values from database table. if the primary-key or any coloumn is set to auto-increment, the data-table will have those latest value post recent update.
Now you can Call the update as pug.Update(dsUserGroup.ProgramUserGroup);
Read latest values from the ProgramUserGroup coloumns and assign respective values into the child table before update. This will work exactly the way you want.
alt text http://ruchitsurati.net/files/tds1.png

Categories