Entity framwork better error explanation - asp.net-mvc

I'm using a databasefirst approach with Entity framwork and MVC 4(asp.net) and do now and then get the following error:
The operation failed: The relationship could not be changed because
one or more of the foreign-key properties is non-nullable. When a
change is made to a relationship, the related foreign-key property is
set to a null value. If the foreign-key does not support null values,
a new relationship must be defined, the foreign-key property must be
assigned another non-null value, or the unrelated object must be
deleted.
Most likly I have an unintentional null-reference which comes is due to any part of the conversion step(from view, to viewmodel, to databaseobject through automapper).
What I would like to know is if there are some way to get the information WHERE the problem is, which foreign key that is causing the issue. I have tried tracing the database but it seems like the application knows before trying to save to database that there are issues. Can I somehow debug this? Get more error info?

These type of errors can be frustrating because they can be hard to track down.
I would start with purging all the data from the database (back it up if required).
Then, open the database in Management Studio and drag and drop the tables onto the visual designer. Then you get a visual clue of what the relationships look like. You might get a surprise!

These type of errors may be occurred if you changed your database schema(model) and your database have some data.
two or more tables have relationships using foreign key.
Possible Solution
drop the database and apply migrations again.

Related

Updating entity framework model after changing the data type of column in database table

I am working with entity framework 6 with database 1st approach. I changed the datatype of my columns in the table and after updating my model I got the following error:
Error 1 Error 2019: Member Mapping specified is not valid. The type
'Edm.Int32[Nullable=False,DefaultValue=]' of member 'Warranty' in type
'pjModel.Bill' is not compatible with
'SqlServer.nvarchar[Nullable=False,DefaultValue=,MaxLength=50,Unicode=True,FixedLength=False]'
of member 'Warranty' in type 'pjModel.Store.Bills'.
what I understand that there is some compatibility issue between datatypes of framework and sql server.
Also when I opened the .edmx file with XML viewer, it clearly shows that changes are propagated in the model i.e data type has been updated, but in the diagram view when I right click the particular column it still shows the old datatype.
I can provide more information if required.
The issue has been resolved. I manually change the type from the diagram view and then it get mapped with the model class.
Same problem here, using EF6, after changing on a database table a field from int to bit.
It was not enought to delete property from model designer, and create it again, as the table mapping refered to the old type.
I guess this could be useful for similar cases. The only way to solve it (unless you don't mind deleting entity and updating model from database) is to edit your Entity Data Model as text (by default, DataModel.edmx), locate the entity as <Entity> node inside <Schema> node and find the desired property that indicates the old type. As an example:
<Property Name="MyProperty" Type="int" Nullable="false" />
Simply change Type attribute to the desired type, return to Visual Studio, save the edmx file, and rebuild.

Remove entries from a table that maintains a many to many relationship asp.net mvc entity framework

I am writing an application based on an existing database. I have two tables, a server table and a support table (people who support the specified server). These tables can have a many to many relationship, and as such I cannot maintain a foreign key within one of the tables pointing to another.
The solution that the person who designed the schema came up with was to add a third table, a server support junction, that has just two columns - ServerID and SupportID, both foreign keys pointing to their respective table.
When I import this database schema into Entity Framework, it gives me the following warning:
Warning 2 Error 6002: The
table/view 'dbo.Server_Support_Junction' does
not have a primary key defined. The key has been inferred and the definition
was created as a read-only table/view.
As such, the table does not appear in the edmx model and it does not create a class for the table.
As part of the application, I would like the DBA to be able to delete a server or a support (they leave the company/no longer support a certain server/etc). Is entity framework smart enough to see that this table is purely relational and will remove any connections when a support or server is deleted? Or must this be done explicitly?
If it must be done explicitly, what is a workaround for this? I tried adding a primary key called RelationID to the table, but it yelled at me saying that the primary key was not mapped or something.
Gert Arnold helped to find the solution. First, a primary key was added to the table consisting of both the Foreign keys, the SQL was:
ALTER TABLE dbo.Server_Support_Junction
ADD CONSTRAINT pk_ServerSupportJunc PRIMARY KEY (ServerID, SupportID)
I then updated the model by opening the edmx, right clicking on the blank space -> update model from database -> refresh -> finish.
To delete the relationship in the controller, the code was as follows:
Support support = db.Support.Find(id);
support.Servers.Clear();
db.Support.Remove(support);
db.SaveChanges();
Obviously you should do some error checking to make sure the entity was actually found, but that's the gist of it!
Special thanks to Gert Arnold!

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.

Passing a constant value to a stored procedure mapping in Entity Framework

I'm working on creating an Entity Framework model for our database tables, and for the most part, things are going pretty well. However, I'm running into a bit of an issue mapping the stored procedures. See, the homebuilt ORM that our company has been using tends to use one sproc for inserting and updating, and differentiats the operations by passing a bit valued parameter called #IsInsert (I know, don't get me started). Entity Framework seems to expect separate sprocs for inserting and updating, so I figure that all I have to do is tell EF "pass true for this parameter when you're using it as an insert, false if it's an update". However, at least according to the designer UI, it doesn't seem to give me the option for any mapping other than fields on the entity object. Is there a way to pass a constant value (boolean true or false) to a sproc mapping in EF4?
Your best bet may be to use context.executestorequery(query) and keep it how it was before.

Resources