Edit delete in webgrid Asp.net MVC5 - asp.net-mvc

I have created webgrid table and it is fetching data from SQL View (data is coming from database view) everything is working fine except edit and delete. Getting error:
An exception of type 'System.ArgumentException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: The number of primary key values passed must
match a number of primary key values defined on the entity.
how can I fix it? I know I can not add a Primary key in View but I just tried to add Primary key on ID column but it did not let me do it.

Based on the exception message, for example, the entity being updated has 2 columns that are the primary key, but only 1 is being passed in or vice versa. It's hard to tell without seeing any code though.
The view shouldn't matter about whether a primary key exists or not; the controller should be the main component that is in play here?

Related

MVC 5 EF 6 Insert Multiple Rows SaveChanges

I am trying to insert multiple rows using the following code. SaveChanges() works for the first record but if fails when it tries the next one. My guess is that each time it is trying to insert all records. Not sure if this is correct or not, and if it is correct how can I change the code to make it correct. Following is my code:
Contrroller:
foreach(var m in pms)
{
_pmService.AddPms(m);
}
And in _pmService.AddPms:
_pmRepository.Add(pm);
_pmRepository.SaveChanges();
_pmRepository.Add (actually this is from BaseRepository and pmRepository extends this Base)
_ctx.Set<T>().Add(entity);
Finally, here is my SaveChanges() (again this is also from BaseRepostiroy)
_ctx.ChangeTracker.DetectChanges();
return _ctx.SaveChanges();
So in controller, I am looping through each entry, and then calling Add. The Add in service is calls Add in BaseRepository and then it does the SaveChanges(). For first record it works without any issues but 2nd record onwards it fails. And following is the error:
"Saving or accepting changes failed because more than one entity of type XXXXXXXXXXXXX have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption\" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration."
And I am using DatabaseFirst approach.
I found the answer it is with StoreGeneratedPattern. I had to set this Identity in edmx file for the primary key field and it worked.
StoreGeneratedPattern="Identity"

MVC Error on ID as Primary Key

I am new to C# and Razor, and I having some trouble with Id as primary key (using EF). I am setting (Is Identity) as off and I want to record some random number for the field, but it keeps giving me an error:
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code
Additional information: An error occurred while updating the entries. See the inner exception for details.
When I set id as nvarchar it is ok, or if I set another field as primary key for example Name (nvarchar) then id (int) works, but once again I need to keep it as primary key. So if someone can help. Thanks guys.
Because updating a primary key in your table is never a good idea, you want this field to be excluded from you MVC app and have it autogenerated instead.

EF SaveChanges Error

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_tblStmtTask_StmtBatchID". The conflict occurred in database "CRM", table "dbo.tblStmtBatch", column 'ID'.
The statement has been terminated
I"m getting this error while saving a modification to 'tblStmtTask' .. I understand that I have a foreign key to the 'tblStmtBatch', but I haven't a clue why changing an unrelated column in the task should have any impact on the batch.
How do I decipher what the root cause of this error actually is ?
Place a breakpoint on the update statement. The FK property will be empty. In order to find the step where it is set to empty your best bet is to breakpoint the point of creation of the entity and step through it so can pinpoint the place where the FK gets set to empty.
If the FK property is empty at creation there has been a problem with mapping. If the entity is being created with the DefaultModelBinder, make sure you have provided the FK property in your form as well, e.g. using the #Html.HiddenFor HTML helper.

constraint exception happening before client side validation in mvc3 app using ef model first

I'm new to MVC & EF but I am getting a "ConstraintException This property cannot be set to a null value" on a particular entity when I test the client side validation. I generated the ef model from an already existing database. The table in question (ItemTypes) has a primary key that is referenced in 2 other tables (Items and ItemTypeAttributes respectively).
If I try to create an Item after filling in no fields I get a client side validation firing off, the text box turns red and i get the correct validation message. Now if I try to create an ItemType without entering a name, I get the ConstraintException, and THEN after hitting resume in Visual Studio, I see the client side validation error message and red text box.
The message says to relax or turn off constraints in the Dataset, be sure you are not trying to assign a value to a primary key field ... and clear datasets before loading them from view state.
Please advise.
-- edit --- about 20 minutes later I decided to remove the foreign key constraint from the db and update model from database. This works but it's not what I ultimately want. I would like to have referential integrity between the tables. So I can continue testing other parts of the application but I'm sure there are other relationships in my schema that I will come across with similar issues.
I had a similar problem and after further investigation was able to solve this by ensuring the properties in my entity were set to be nullable.
See my answer for further details.

Linq to SQL replacing related entity

I have a Client entity and PostCode entity in Linq to SQL model. The Clients table in database contains client_postcode column which is a FK column to postalcode column in PostCode table, which is a varchar column primary key for PostCode table.
When updating Client, in my code I do this
// postcode
updating.PostCode = (from p in ctx.PostCodes
where p.postalcode.Equals(client.PostCode.postalcode)
select p).First();
where client object is provided from ASP.NET MVC View form. This code seems to set the PostCode related entity fine. But when calling SubmitChanges() I receive the following exception:
Value of member 'postalcode' of an object of type 'PostCode' changed. A member defining the identity of the object cannot be changed. Consider adding a new object with new identity and deleting the existing one instead.
So I am currently unable to change the related entity. How is that done in Linq to Sql?
UPDATE:
After further review and troubleshooting I found out that the problem is in ASP.NET MVC UpdateModel() call. If I call UpdateModel() to update the existing entity with the edited data, something is wrong with the FK assignement for PostCode. If I don't call UpdateModel and do it by hand, it works.
Any ideas what goes wrong in UpdateModel() that it can't set the relationship to foreign key entities correctly?
I am updating this question and starting a bounty. The question is simplified. How to successfully use L2S and UpdateModel() to work when updating items (with related entities as FK) in ASP.NET MVC Edit views?
It seems to me that you are receiving PostCode.postalcode in the http post request.
Based on how model binding works, the UpdateModel call updates .PostCode.postalcode of the model you are passing to it.
Use this overload to include or exclude specific properties.
Wouldn't updating.client_postcode = client.client_postcode; accomplish what you want?
Client.PostCode should be looked up on seek based on client_postocde.
You can not do what you are trying, you cannot change the Postcode like that.
James' idea is in the right direction.
Updatemodel() takes the matching values from the Formcollection
How do these values come in the Formcollection? What are their keys?
basically there are 2 ways in editing an object.
option 1:
all the value names you want to update have corresponding keys in the Formcollection, which leaves you just to call UpdateModel() of the original object. do SubmitChanges()
option 2:
Get the original object, change it's values manually (because the keys dont correspond) and do SubmitChanges()
you are tying to change a link, you cant do that. you can only edit the updating.client_postcode which in this case is a string?
Can you please copy the whole action here? So I can write some code for you without gambling.

Resources