How to update primary key value in entity framework? - c#

I have table(and also entity in Entity Data Model) Person with following fields:
Name Type
SocialID String
FirstName String
LastName String
which SocialID is Primary Key. I want to update value of SocialID for each record. However when i try to update this field in Entity Framework I get following error:
The property 'SocialID' is part of the object's key information and cannot
be modified.
The code that i get above error is:
foreach (var p in Entity.Persons)
{
p.SocialID= p.SocialID + "00";
Entity.SaveChanges();
}
How I can do this??

As mentioned by the others, you can't do it in code. You will have to make your update in SQL. Either in a migration or directly in SQL Server Management Studio (or the equivalent if you're using a different database).
UPDATE Person -- Or 'Persons' if that's what your table is called
SET SocialID = SocialID + '00'
It will require a lot more work than this if you have other tables use this column as a foreign key (you'll have to drop the constraints first -- on all tables that reference your primary key -- then fix the data and recreate the constraints). Or as Moe said in the comments, you can set your foreign keys to cascade on update.

As per my knowledge primary key once generated cant be updated programatically,that defies the purpose of primary key.
It'll be better if you insert all your data again with new primary keys and delete old data.

Why would you want to change the primary key? Entity framework will be using that field to identify the object, you can't change its value while it is the primary key.
Based on the first answer I suggest you change the table Person to have its own primary key, let's say PersonID and mantain the SocialID as a foreign key to the Social table. If you need a person to have several Social records you may need to create other table to correspond the PersonId to several SocialId, removing the SocialId from the person table.

Related

C# Entity Framework: Update Query Does not work

I have this simple code : (update value)
I'm trying to update column "c"
using (MaxEntities ctx = new MaxEntities())
{
aa orders = (from order in ctx.aa
select order).First();
orders.c = 22;
ctx.SaveChanges();
}
this is the table :
CREATE TABLE [dbo].[aa](
[a] [int] NULL,
[b] [int] NOT NULL,
[c] [int] NOT NULL
) ON [PRIMARY]
and values inside :
but i get an exception :
The property 'c' is part of the object's key information and cannot be modified.
I'm new to EF.
any help will be much appreciated.
The property 'c' is part of the object's key information and cannot be modified.
That's why you can't edit it. Maybe you need to add id column as a key with identity specified
As explained in another answer EF must uniquely identify every entity. If you don't have PK in the database, EF will infer some key. Key is considered as fixed so if EF inferred c as part of the key (and it did it because it uses all non-nullable non-binary columns) you cannot change its value. Moreover EF takes all tables without primary key as readonly so even if you remove c from the key in the designer and modify c value you will get another exception when you execute SaveChanges.
The reason for the second exception is in the way how EF describes model and the database. When EF inferred key, it did it only for description of your entities and for context's internal needs but not for description of the database. When EF tries to save changes it builds UPDATE statement from database description and without information about real database PK columns it will not be able to identify correct record for update (every update in EF can affect only single record - EF checks ROWCOUNT). This can be solved by cheating EF and updating its database description = by describing some column in the table description as primary key. This leads to multiple problems:
You must have some unique column in the database otherwise this method will not work.
You must edit EDMX manually (as XML) to add this change
You must not use default MS EDMX designer for updating your model from database because it will delete your change
Simple advice: Either use database tables with primary keys or don't use Entity framework.
Primary key missing here. Add primary key in table and it work.
I believe if there's no PK at all, EF uses all of the fields/columns as part of the key info.Here's a nice explanation: by #SteveWilkes of why. But what do your entities look like? The other possibility is that it doesn't have a property because the association is inside a different entity, if this is a foreign key.
EDIT
This got me thinking. There are just going to be situations where you have to work with legacy tables having no PK, even if you would never create such a thing. What about views? EF is a mapper - it has to uniquely identify that record so it infers and defines this key. Yes, you could use stored procedures, but could you also hack the XML and remove the keys from the table definition?
AND EDIT AGAIN
After posting this, I see #Ladislav Mrnka already said a similar idea (cheating EF and updating its database description), so it has been done (WARNING: Consume at your own risk - never tried). Quick google got me this blog with clear instructions:
Close the model designer in Visual Studio if it is still open and re-open the .edmx file in an XML editor
Find the edmx:StorageModels -> Schema -> Entity Container -> EntitySet element that refers to the table in question
On the EntitySet element, rename the store:Schema attribute to Schema
Remove the store:Name attribute altogether
Remove the opening and closing DefiningQuery tags and everything in between them
Save and close the .edmx file
But really, who doesn't like a PK? Can you not add an id?

Deleting multiple tables from SQL Server 2008 using Datalist C#

This may seem a common question but I googled to find the right answer that can fix my problem and failed to do so.
I have multiple tables connected to each other by ProductID and I wish to delete all data from them when the product from main table has been deleted. i.e.
Products : ProductID - Vender - Description
ProductRatings : ProductID - Rating - VisitorsCount
ProductComments : ProductID - VisitorName - Comment
I read that for such situation a SQL trigger is used but I have no idea about it besides I might be mentioning my DataSource in ASCX.CS file in some cases and in some cases I might simply use SqlDatasoruce in ASCX file. Is there any query or stored procedure that can be used?
The easiest way to do this is to implement a foreign key relationship to ProductID and set on delete cascade. This is a general idea:
create table ProductRatings
(
ProductID int not null
foreign key references Products(ProductID) on delete cascade,
Rating int not null,
VisitorsCount int not null
)
What that does is when you delete a primary key value from the Products table, that causes SQL Server to delete all records that have a foreign key constraint to that primary key value. If you do this with your ProductComments table as well, problem solved. No need to explicitly call a DELETE on any records in the referencing tables.
And if you aren't using referential integrity...you should.
EDIT: this also holds true for UPDATEs on the primary key. You just need to specify on update cascade, and the foreign key references will update as the primary key did to ensure RI.

Inserting relational data with Linq to SQL results in duplicate entry error

I have drawn up a database design in the Visual Studio database diagram editor, and created all of my tables from that. I also created a Linq to SQL class and added my tables to create objects for each table. I am running into an issue when trying to insert new entries to the database.
For example:
Let's say I have two tables, Artists and Albums. A single Artist can have multiple Albums (one-to-many). Album has an ArtistID field which is a FK to the ArtistID PK in the Artist table. Their IDs are GUIDs which are auto generated by the database.
Now in my code I create a new Album object (called myAlbum) and set its Artist object to an Artist that is already in the database (myArtist).
If I do something like this:
DatabaseDataContext context = new DatabaseDataContext();
context.Albums.InsertOnSubmit(myAlbum);
context.SubmitChanges();
I end up getting a SqlException saying: "Violation of PRIMARY KEY constraint 'PK_Artist'. Cannot insert duplicate key in object 'dbo.Artist'.
The statement has been terminated."
If I compare myAlbum.Artist to the Artist already in the database, Linq says they are equal, so it knows they are the same object.
How do I get Linq to insert the new Album object and link it to the existing Artist in the database already, without trying to insert the Artist again?
Apparently, you set the Album's Artist property with an object that was fetched with an other datacontext instance. Therefore, your new DatabaseDataContext "thinks" the Artist must be inserted.
You can either set Album.ArtistId (not the Artist object), or fetch the Artist in the same data context and add the album to its Albums collection.
By the way, using (var context = new DatabaseDataContext()) { ... } is better.
You need to solve the duplicate primary key first and with my test I created my primary table with a primary key of UNIQUEIDENTIFIER and with a default value of (newid()).
Then when you drag your table into your Linq To SQL class project, the table class is created with everything you wanted except: The Primary Key Column should have its Auto Generate Values set to true but its not! By default is false when your column data type is of type UNIQUEIDENTIFIER.
Then I dropped the column in MS SQL and recreated it with a data type of INT dragged it into the Linq to SQL class and it then set the column property Auto Generate Values to true.
So if you use the UNIQUEIDENTIFIER you need to manually set the Auto Generate Values property to true.
I think that the duplicate primary key may be GUID.Empty. If my understanding is correct.
I would think solutions for this problem.
set default value of the pk_artist column to be newid(). That allow the primary Kerr auto generated.
Or
Explicit assign primary key to entity.
myAlbum.Pk_Artist = GUID.NewGiud();
context.Albums.InsertOnSubmit(myAlbum);
Hope this help

Table-per-type inheritance insert problem

I followed this article on making a table-per-type inheritance model for my entities, but I ran into some issues. Below I'm posting steps to reproduce the problem I'm having in a minimal environment to rule out other factors.
First, I created a new MS SQL Server 2008 R2 database with the following two tables:
Users
Id : bigint (PK and set it as the identity column)
Name : nvarchar(25) NOT NULL (whatever, some random property
Customers
Id : bigint (PK, identity column, and FK on Users.Id)
Title : nvarchar(25) NOT NULL (also whatever, some random property)
Next, I generated the .edmx entity model from the database, and followed the link at the top verbatim. That is to say, I deleted the association between User and Customer, set User as the base class of Customer, deleted the Id property from the Customer entity, and made sure that the Customer.Id column was mapped to the inherited User.Id property. I then ran the following small program:
using (var db = new EF_Test.testEntities())
{
var cust = db.Users.CreateObject<Customer>();
db.Users.AddObject(cust);
db.SaveChanges();
}
I get the following error when I make that last call:
"A value shared across entities or associations is generated in more than one location. Check that mapping does not split an EntityKey to multiple store-generated columns."
With the following inner exception:
"An item with the same key has already been added."
Any ideas on what I could be missing?
A quick google on the error message turned up the following solution, maybe it helps you:
http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/4bfee3fd-4124-4c1d-811d-1a5419f495d4
I think that I figured it out. The
table for the Party sub type had its
key column set to autogenerate a key
value and since it's derived, the EF
wanted to set that value explicitly.
So have you tried removing the "identity" setting from the customer table? So it doesn't autogenerate the primary key?
Hope this helps.
I finally found the source of my troubles. For those still interested, in the Customers table, the Id column should not have been set to the identity column of the table (PK and the FK dependency are fine though).
Why you don't want to make a foreign key (UserId) as a separate column? Maybe it can help you.
Also try to use model first approach and generate db after model creation as it is described in the following article.

The property 'text' is part of the object's key information and cannot be modified

So I have a table in the database, with a column that is simply an nvarchar(800).
When I try to do:
try
{
UserTable = (from x in entities.userTable where x.uID == uID select x).Single();
UserTable.DateCreated = DateTime.Now;
UserTable.text= newText;
Update(UserTable);
}
I get the exception in catch: "The property 'text' is part of the object's key information and cannot be modified."
When I look into the table, I don't see anything under "key" or "index". So it's not a key, I don't understand why C# is giving me incorrect information. Nothing in SQL Management Studio says anything about "text" being a key or index. What do I do?
Is there a PK on the table at all? If not, EF uses all of the fields/columns as part of the "key information."
View the data model by double clicking on the edmx file under the Models folder.
Make sure the keys are properly mapped. If you right click on a column you can toggle the Entity Key property. Once the column in question is not marked as entity key you should be able to update the value.
Follow these simple steps
Step 1: Check whether your table is having primary key column in database or not. If it does not have any primary key then add a primary key. Because if we don't add a primary key to table than entity framework creates its own key collection and add all columns in it.
Step 2: Open your .edmx file to see table object mapping. You will be able to see each column of table is having icon like primary key. So Write click on your page and update .edmx from database.
Step 3: If you still see same primary key icons on all columns than click on column name you want to update one by one and go to property window and Set Entity Key property to false.
The problem here is that Entity Framework cannot make changes to the primary key of the particular table. Now if you have not specified a primary key for your Table, entity framework will consider everything as the primary key, and thus you won't be able to make changes to the table. What you need to do is, define a primary key in the table, delete the table from your model from the Model Browser, and then re-add the table in the model. This shall surely fix it. Happy coding. Cheers!

Categories