I have a table Transactions with 4 Foreign Key references to an Employee table - all nullable INT fields. I create a record in Transactions with 3 of the Employee fields populated. If I then update the remaining null Employee field I get the error:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.GetOtherEndOfRelationship(IEntityWrapper wrappedEntity)
I found this SO question which helped me identify the cause, but I still don't understand WHY it happens - Can anyone explain the reason it occurs?
My workaround is to make sure all Employee FK fields are populated on creation of the Transactions.
EDIT - this is not a duplicate- it has NOTHING to do with a simple check for null.
Related
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.
New to EF and trying something out with "Database first".
Error 3025: ... :Must specify mapping for all key properties
(PurchaseUsers.PurchaseUsersId) of table PurchaseUsers.
I have in my db 3 tables:
Purchases Participants PurchaseUsers
PurchaseId ParticipantId PurchaseUsersId
... ... PurchaseId
ParticipantID
The table PurchaseUsers is to know which participant(s) is(are) using a purchase.
At first I didn't had the PK on that table but then I got the following error when trying to save a Purchase.
After googling a bit I found out that I had to add a PK to avoid this error.
Unable to update the EntitySet 'PurchaseUsers' because it has a DefiningQuery
and no <InsertFunction> element exists in the <ModificationFunctionMapping> element
to support the current operation.
But adding the PK created the mapping-error and I just can't figure out how to solve this or create a mapping.
The table PurchaseUsers itself isn't visible in my .edmx model, but it's listed in the Store in the Model Browser.
Thanks.
UPDATE
Changed the name of a column in the database today. "Update model from database" added the new columnname to the table in the model, but did not remove the old one.
Had to start from scratch once again.
Looks like the update-function is not working very well.
This is weird. Updating the model from the database should make the model and the database to by in-sync. Try deleting and recreating the model from scratch.
I have a one-to-many relationship defined for two entities, let's just say Customer and Order. The relationship states that a Customer object can have many Order objects, but that an Order must have one Customer...a pretty standard 1:M relationship.
I have no cascading rules configured on the database and OnDeletes are set to None in my entity data model. This means deleting a customer that has orders will not be allowed.
My problem is that when the user in my application deletes a customer (that may have orders), I want to catch the exception that is thrown by enforcing the foreign key constraints. For one specific customer that has 33 orders, I get InvalidOperationException but for another customer that only has 2 orders, I get UpdateException. EF is letting the second delete statement go to the database and the database is returning the error that EF makes the UpdateException for. In the first scenario, EF doesn't even let the delete statement go to the database, it just says this is going to be invalid, because this entity instance of Customer contains Orders.
Can anybody explain why this behavior is happening?
There can be two different exceptions because there are two layers where this check is applied. First if you mark an object as deleted and execute SaveChanges EF will check its internal storage where all loaded objects are tracked. If EF finds that any tracked order related to the deleted customer is also not marked as deleted it will fire an exception (probably InvalidOperationException). If there is no tracked related order EF will execute delete operation in the database where FK relation triggers an error. This error is captured by EF and an exception is throwm (probably UpdateException with inner database related exception).
I tried setting up a simple one-to-many relation in Entity Frameworks designer.
The tables are Category (1) and Transaction (N). Here's what I did:
Add "association"
End1 = Category, multiplicity 1, navigation property=Transaction
End2 = Transaction, multiplicity Many, navigation property = Category
Building it gave me the error "No mapping specified". Ok, makes sense. So I added this mapping:
Category
Category.CategoryID = Transaction.CategoryID
But the mapping designer also automatically adds a mapping for the Transaction table, which I cannot figure out how to delete or how to setup:
Transaction
Transaction.TransactionID = ???
Leaving it empty seems most valid, but that gives me: Error 3024 "Must specify mapping for all key properties (TransactionID)"
And trying to set it to a fake int property just hoping it's a compiler bug. But that gives me errors 3002 and 3003.
I dont get what to do. Isnt Associations meant to be used this way?
I suggest creating (or importing from the database) an entity for Catagory and an entity for Transaction. Add scalar properties to each as needed. Next, right-click on your entity, click Table Mapping, and map your entity properties to the table fields. For example, for the Category entity, map CategoryID field to a CategoryID property. Do the same for the other entity. THEN create the association.
Note that associations linked by exposed foreign keys do not have any mappings.
BTW, you'll probably want to add navigation properties as well.
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.