How can this scenario cause an UpdateException in EntityFramework while calling SaveChanges? - asp.net

I am unable to understand the line in bold from this msdn page:-
http://msdn.microsoft.com/en-us/library/bb738618.aspx
SaveChanges can generate an UpdateException when an object added to the ObjectContext cannot be successfully created in the data source. This can happen if a row with the foreign key specified by the relationship already exists. When this occurs, you cannot use Refresh to update the added object in the object context. Instead, reload the object with a value of OverwriteChanges for MergeOption.
In a table, a foreign key column can have a single value multiple times. e.g. DepartmentID foreign key in Users Table: More than one User can have same DepartmentID foreign key.
So how can this cause an UpdateException ?

Easy. You have an entity in your context in the Added state with a PK value of something already in the DB. This is common when people try to use stub objects incorrectly. If you want more help than that, you need to isolate your problem and post your code.

Related

asp.net Entity Framework/ Update from database/ The table/view does not have a primary key defined and no valid primary key could be inferred

One of the database view I am trying to import using entity framework contains only two columns, one is an integer type of column and another one is an aggregate function. I am getting the following error.
The table/view does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.
I understand it is a known scenario and it can be fixed by either including a Key column in the view or modifying the edmx file manually.
I just wanted to know if there is some other solution other than the above two? I do not want to include an additional column in my query and making changes in edmx is not feasible as DB changes are very frequent and the edmx will be overwritten every time I update from db.
You can mark both properties as entity key directly in the designer but you must ensure that the composite value of these two properties will be always unique. If you cannot ensure that you must add another unique column anyway or you may have some other problems when working with such entity set.

Extending delete method of GridView

I have a page with GridView pulling some data from a SQL Server database via Linq-to-SQL.
I made use of the automatically-generated buttons for deleting. However, in order for the delete command to work properly, I need to somehow make sure that one table in relation with those records I want to delete, is also modified (the related record in it is also looked up and deleted).
Whats the easiest way to do this?
Thanks,
Ondrej
Define a foreign-key constraint with cascade delete.
Delete Rule
Specify what happens if a user tries to delete a row with data that is involved in a foreign key relationship:
No Action An error message tells the user that the deletion is not allowed and the DELETE is rolled back.
Cascade Deletes all rows containing data involved in the foreign key relationship.
Set Null Sets the value to null if all foreign key columns for the table can accept null values.

insert data from a asp.net form to a sql database with foreign key constraints

i have two tables
asset employee
assetid-pk empid-pk
empid-fk
now, i have a form to populate the asset table but it cant because of the foreign key constraint..
what to do?
thx
Tk
Foreign keys are created for a good reason - to prevent orphan rows at a minimum. Create the corresponding parent and then use the appropriate value as the foreign key value on the child table.
You should think about this update as a series of SQL statements, not just one statement. You'll process the statements in order of dependency, see example.
Asset
PK AssetID
AssetName
FK EmployeeID
etc...
Employee
PK EmployeeID
EmployeeName
etc...
If you want to "add" a new asset, you'll first need to know which employee it will be assigned to. If it will be assigned to a new employee, you'll need to add them first.
Here is an example of adding a asset named 'BOOK' for a new employee named 'Zach'.
DECLARE #EmployeeFK AS INT;
INSERT (EmployeeName) VALUES ('Zach') INTO EMPLOYEE;
SELECT #EmployeeFK = ##IDENTITY;
INSERT (AssetName, EmployeeID) VALUES ('BOOK',#EmployeeFK) INTO ASSET;
The important thing to notice above, is that we grab the new identity (aka: EmployeeID) assigned to 'Zach', so we can use it when we add the new asset.
If I understand you correctly, are you trying to build the data graph locally before persisting to the data? That is, create the parent and child records within the application and persist it all at once?
There are a couple approaches to this. One approach people take is to use GUIDs as the unique identifiers for the data. That way you don't need to get the next ID from the database, you can just create the graph locally and persist the whole thing. There's been a debate on this approach between software and database for a long time, because while it makes a lot of sense in many ways (hit the database less often, maintain relationships before persisting, uniquely identify data across systems) it turns out to be a significant resource hit on the database.
Another approach is to use an ORM that will handle the persistence mapping for you. Something like NHibernate, for example. You would create your parent object and the child objects would just be properties on that. They wouldn't have any concept of foreign keys and IDs and such, they'd just be objects in code related by being set as properties on each other (such as a "blog post" object with a generic collection of "comment" objects, etc.). This graph would be handed off to the ORM which would use its knowledge of the mapping between the objects and the persistence to send it off to the database in the correct order, perhaps giving back the same object but with ID numbers populated.
Or is this not what you're asking? It's a little unclear, to be honest.

Update Data Model Business Entity

I have web application where Iam using linq to business entites i have business data model.
the problem is :
I have table with one column that it dosen't allow null value, when I try to update this table the folloeing error arise:
error The property 'e.g Carrier' is part of the object's key information and cannot be modified
what I can do?
The easiest thing to do is add a second column to the table that has a unique key eg guid and create a read only property on the entity that corresponds to it.
Linq to business entites needs some kind of key to keep track of what to update in the database. Usually this is the primary key on the database table. If you dont have a primary key it cannot reliably update the database and will then send you an exception.
Also if there is no primary key explicitly set on the table linq to business entites will select one of the columns (think its the first column in the table but i could be wrong) to act as a primary key and will therefore not allow you to update it.

Cannot insert null where field is Guid (object in SqlDataSource)

I have a table which links to another table in the ASP.NET membership schema.
Problem is, all the PKs for the ASP.NET tables are uniqueidentifier so mine has to be too. When I add a SqlDatasource and call its Insert() method, I get the following error:
Cannot insert the value NULL into column 'DiscountCode', table 'CreamDb.dbo.CustomInfo1'; column does not allow nulls. INSERT fails.
The statement has been terminated.
The uniqueidentifier is also treated as an object (its data type), but there is no Guid data type. I had this problem before, but the schema was much simpler so I could fix it.
How can I go about fixing this? If I get rid of the data type part in the markup (so just leave the field/parameter name but not the data type stuff), I get another error so that is not possible.
Thanks
What do you mean by "there is no Guid data type"? What's wrong with System.Guid? Can't you just use Guid.NewGuid(), set the field appropriately, and do the insert?
EDIT: Just to give a bit more meat: attach an event handler to the Inserting event, and populate the field then, via the DbCommand returned by SqlDataSourceCommandEventArgs.Command. Or change the SQL used by the INSERT command to ask the database to populate the GUID field for you.
A popullar approach when dealing with references to the ASP.NET Membership Provider's data is, instead of keeping a proper foreign key to the GUIDs, instead store something like the LoweredUserName in your table. Then, use the Membership Provider's API to interact with the object you need. In some cases, you need an ObjectDataSource abstraction layer to accomplish CRUD scenarios.
Set the default value of the column in SQL Sever to "newid()".
Asp.net won't send the value, and the field will get a new guid.

Resources