get identity when adding via entity framework - c#

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.

Related

Self-referencing primary key on insert

When I insert a new record and it auto generates an auto identity value. I then have to subsequently update a column in the same table with that same id that was generated on initial insert. The only way i can see this being accomplished is to first save, get the new PK and then do an update. However is there any other way this can be accomplished in 1 database call? I know I can accomplish this with a stored procedure rather easily, but I don't have that option at this point. See table structure below.
Person
PersonID Int (Auto Identity)
FirstName
LastName
HeadOfHouseholdID int (FK to PersonID) in this table
is there any other way this can be accomplished in 1 database call?
A trigger or custom SQL query would work. But it's probably not worth worrying about.

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

insert data in no identity number column

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

Writing to the database from LINQ in C#

I am trying to write some content to my database via LINQ. Currently, I'm getting the following error:
Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF.
I understand this is a primary key related issue. My table has the identity specification set to "Yes" with Identity Increment set to "1". But I have successfully updated other tables using code that looks like the following:
using (DataModelDataContext context = new DataModelDataContext())
{
List<MyTable> newRecords = new List<MyTable>();
MyTable record1 = new MyTable();
record1.CreatedBy = GetUserName();
record1.Information = GetInformation();
newRecords.Add(record1);
MyTable record2 = new MyTable();
record2.CreatedBy = GetUserName();
record2.Information = GetInformation();
newRecords.Add(record2);
context.MyTables.InsertAllOnSubmit(newRecords);
context.SubmitChanges();
}
What would cause this error? If I want to write new records, is there a way to set the primary key before it gets sent to the db? Something like "GetNextKey()" or something? Basically, I just need to insert these records. What am I doing wrong?
Thanks!
The code you have posted would work, assuming neither of those fields have the identity value. You basically need to assure you do not try to set the identity value before you add the item to the Table collection. (actually, you should never set the identity value from your code in most circumstances when it is to be generated in the DB).
So somewhere, the code that is having an error is trying to set the identity field's value.
If the ID is important (say you're importing data, and records you'll be inserting later will reference these records), then turn off the identity temporarily while you perform the insert. If having a particular ID on each record doesn't matter, and you can let the identity column pick one (which is 99.9 percent of the time), make sure you're not specifying a value for the ID before trying to save the record. Also make sure that your mapping between the object and the DB specifies that the ID is an identity, so EF knows not to try to insert the ID column.
Check to make sure your primary key/identity column has the following set within the DBML:
Auto Generated Value: True
Auto-Sync: OnInsert
This will make sure that LINQ-To-SQL will not try and insert the key value into that column and that it will update the value after an insert takes place. These should be on when you added the table to the DBML.

Entity Framework 4 Returning KEY/Primary Key

Entity Framework 4 Returning KEY/Primary Key
I’m Trying to find a way to Return a Key/Primary Key without having to create a stored procedure to do it for me using:
CREATE PROCEDURE [dbo].[UserRecords]
(
#Name varchar(10)
) AS
-- INSERT the new record
INSERT INTO MyTable (Name)
VALUES(#Name)
-- Now return the InventoryID of the newly inserted record
SELECT SCOPE_IDENTITY() AS ID
Though Visual Studio 2010 I then Use the Add Function Import From the Model Browser and Create a Complex Type.
Then Though C# i use the Following Code to check its working.
SQL_DB_Entities DB= new SQL_DB_Entities();
var ReturnValue = DB.UserRecords("BOB").First();
Console.Write(ReturnValue.ID);
Console.Read();
I'm simply looking for a better way to return the ID and also being very sure im not going to cause head aches for myself laster on down the track.
If you feel this is not the best way to return the key please let me know.
I have Tried it this way but returns 0
SQL_DB_Entities DB = new SQL_DB_Entities();
User UserObject = new User{Name = “BOB”};
DB.AddToUserTable(UserObject);
DB.SaveChanges():
Int key = UserObject.ID;
Console.WriteLine(key.ToString());
I should also mention that the DB is looking after the Primary Keys not my application.
If you correctly setup StoreGeneratedPattern to Identity in your entity and if you have autogenerated PKs in the database, EF will fill the Ids of your inserted entities after each save changes. Check this article to understand store generated pattern.
Normally PKs are dealt with as a particular property on an EF Object EntityKey. You are probably best to have a look at EntityKeys.
The usual way is to set the StoreGeneratedPattern property of the PK column in your model as Identity. Or if you are using code-first, annotate the property with:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
I am not sure whether this works with sprocs, though. By the way, any special reason you are using sprocs in this case?

Categories