insert data in no identity number column - c#

I have a table in my database.
This table has one column named A, the column is not entity or auto number, unique key or...
I created a model from my db with Entity Framework 4.1.
My code
using (var contex = new testEntities())
{
Table_1 t = new Table_1();
t.A = 1;
contex.Table_1.Add(t);
contex.SaveChanges();
}
I do not want to use the identity number or index in my table.
When I want to insert a row in it it gives me this error:
Unable to update the EntitySet 'Table_1' because it has a DefiningQuery and no
<InsertFunction> element exists in the <ModificationFunctionMapping> element to
support the current operation.

You either have to give the table a primary key (which you don't seem to want to do) or you need to provide a function to tell Entity Framework how data can be inserted into the database.
I would strongly suggest that you put a primary key on your table unless you have a very good reason for not doing this, and in all my years I can't think of many instances when I wanted a table without a primary key.
If you don't want the primary key at all, then you might find this article useful about using Stored Procs for INSERTing data into the database: http://msdn.microsoft.com/en-us/data/gg699321.aspx

Related

Checking for duplicate rows using Entity Framework in C#

Using Entity Framework 6.x. For some entities after I create a new instance of an entity object and populate it with data values, I would then like to be able to trigger a lookup on the database. I would like to see if a row exists with all the same values that where populated into the entity object and if it exists return the primary key.
It seems logical that there should be a standard way to do this built into the entity framework but I can't find it. It would be nice if there was a method that would just take any entity object and return the primary keys of any matching rows.
What's wrong with just doing a FirstOrDefault() filter to retrieve an entity with matching values?
var entity = new Entity { // initialize some properties }
var matched = dbContext.EntityTable.FirstOrDefault(x => x.PropA = entity.PropA && x.PropB = entity.PropB);
(Don't have EF on my machine right now, the actual access code is just psuedo)
This is not possible. You have to create query with all data values that you want to check. Another option is to have checksum column that contains some hash from all values (without the primary key), then you can compute the hash from newly created entity and query database if entity with such hash exist.
Edit: Additionaly there is an option to create multi column Constraint in SQL Server (check this: Unique constraint on multiple columns), but it doesn't return primary key of duplicated row in a convenient way.

Insert a specific id into auto incremented field in MySQL with Entity Framework 5

So this i my situation.
I have an old database with a lot, and I mean a LOT of data. However I've ended up creating a new database structure and now I want to move data from the old database into the new one. Being a programmer I'm not keen on doing it manually which is why I made a program to do just that.
Now here is my problem: When adding a new item into the new database I'm unable to set it's id, which is crucial for the different link references and general foreign key references that exists in the old database.
My question is therefore: How would I be able to insert an specified id integer into a field that has auto_increment in my MySQL database via Entity Framework 5 which uses database first in C#?
This is my MySQL script for the new database:
CREATE TABLE Profile
(
_id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
UNIQUE KEY(_id),
etc etc
)
My insert code:
public Profile Add(Profile item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
db.Entry(item).State = EntityState.Added;
db.SaveChanges();
return item;
}
On an end note I whould like to inform that I know this is bad practise in general, but the database is empty and the id inserted are auto generated and unique from the old database which will ensure that no dublicates will occour
You have to turn off identity insert, insert the records then turn on identity insert back
The solution I found where to alter the table before inserting into it. It's basicly the solution other people gave, however I needed to make a few turns.
This is what I did:
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE Profile DROP PRIMARY KEY,
MODIFY _id INT PRIMARY KEY NOT NULL;
insert commmand here....
ALTER TABLE Profile DROP PRIMARY KEY,
MODIFY _id INT AUTO_INCREMENT PRIMARY KEY NOT NULL;
SET FOREIGN_KEY_CHECKS=1;
I came into the same problem except using Entity Framework 6, this is how I solved it:
Go into your Entity Model
Select each auto_increment field and in properties set StoreGeneratedPattern to None

get identity when adding via entity framework

I'm using entity framework to insert a new record into my templates database. I would like to know what the identity of the inserted record is after the insert is done.
my code for inserting the record...
WEBSITE_ORDER_LINE_TEMPLATES newTemplate = new WEBSITE_ORDER_LINE_TEMPLATES();
newTemplate.customerNo = Customer.CustomerNo;
newTemplate.templateName = txtSaveTemplate.Text.Trim();
dpot.WEBSITE_ORDER_LINE_TEMPLATES.Add(newTemplate);
i want to know what the templateId is... in sql, this field is set as primary key and IsIdentity=Yes.
is there a quick way to get this value without searching the database where customer and templatename match? I need to know the ID because after this part, i want to enter template line information and there's a foreign key on that table on the templateId in this table.
Call the SaveChanges() method. EF updates the newTemplate.templateId with SELECT SCOPE_IDENTITY() after the INSERT.

delete data from table with no primary key using EF database first

I am working on EF database first application and I have encounter the situation where delete records from a table which has no primary key.
I have no control over the database and it is not possible to add any key for the DB table.
What is the best approach I can take?
The best approach is ,you need add a primary key.
Why EF need you add a PK?
Because, PK is a only way to identity the row in the table , if not exists a PK , the table may have many same rows(if have PK,it's different,PK is unique,each row will be different),so if your want to delete or update ,which row is your target? if not exists PK ,EF couldn't know how to identity the row ,so you must have PK in the table.
If you can't add one (may be the DB is from customer, you don't have permission), you can change the mapping XML file between EF and DB,To add a relate PK Element for a unique table column.

How to update primary key value in entity framework?

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.

Categories