Can't insert NULL value after db export - c#

this is my problem.
i changed db position, first it was on an external server and i exported it on my local position (./SQLEXPRESS)
now i can't make insert record because it says that the record contain NULL id value. But it is correct because it is an auto-increment and i pass "0" or null for tell my db to insert a row (it is db.mytable.add(myrow) and it is the base behavior).
why now it tells me to pass a row with setted id?
this is the simply code
db.Company.Add(company);
db.SaveChanges();
and it give error on SaveChanges
i think it is a db owner problem

You should check your DB again. Maybe the code is looking at the wrong DB, like dbo.YourDB instead of NinoEmma.YourDB. Because it can't find your DB, EF Code First will create one and the id column doesn't auto-increment anymore.

Related

Insert to Oracle Database always creates new Index ID and doesn't take the old one

I am currently trying to insert a DataRow into an Oracle SQL Database. The entry gets inserted into the Database but always gets a new ID. I am providing an ID in the Insert Command but it always uses an auto increment and doesn't let me insert my ID.
What can I do?
There are 2 possible solutions to your problem.
Set column as NOT to be "Identity" column. This will take care of
your issue without any hassle.
If you must keep that column as "Identity" column, set "Generated"
property to "By Default on Null". This will ensure that when you are
NOT passing any value for ID, the system generates next sequence
number automatically.
For solution 2:
DDL Statement: ID NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY INCREMENT BY 1
Table Creation in SQL Developer:

how to use SCOPE_IDENTITY() not in insert

I want to get new id(Identity) before insert it. so, use this code:
select SCOPE_IDENTITY() AS NewId from tblName
but is get this:
1- Null
2- Null
COMPUTED COLUMN VERSION
You'll have to do this on the sql server to add the column.
alter table TableName add Code as (name + cast(id as varchar(200)))
Now your result set will always have Code as the name + id value, nice because this column will remain updated with that expression even if the field are changed (such as name).
Entity Framework Option (Less ideal)
You mentioned you are using Entity Framework. You need to concatenate the ID on a field within the same record during insert. There is no capacity in SQL (outside of Triggers) or Entity Framework to do what you are wanting in one step.
You need to do something like this:
var obj = new Thing{ field1= "some value", field2 = ""};
context.ThingTable.Add(obj);
context.SaveChanges();
obj.field2 = "bb" + obj.id; //after the first SaveChanges is when your id field would be populated
context.SaveChanges();
ORIGINAL Answer:
If you really must show this value to the user then the safe way to do it would be something like this:
begin tran
insert into test(test) values('this is something')
declare #pk int = scope_identity()
print #pk
You can now return the value in #pk and let the user determine if its acceptable. If it is then issue a COMMIT else issue the ROLLBACK command.
This however is not a very good design and I would think a misuse of the how identity values are generated. Also you should know if you perform a rollback, the ID that would of been used is lost and wont' be used again.
This is too verbose for a comment.
Consider how flawed this concept really is. The identity property is a running tally of the number of attempted inserts. You are wanting to return to the user the identity of a row that does not yet exist. Consider what would happen if you have values in the insert that cause it too fail. You already told the user what the identity would be but the insert failed so that identity has already been consumed. You should report to the user the value when the row actually exists, which is after the insert.
I can't understand why you want to show that identity to user before insert, I believe (as #SeanLange said) that is not custom and not useful, but if you insist I think you can do some infirm ways. One of them is
1) Insert new row then get ID with SCOPE_IDENTITY() and show to user
2) Then if you want to cancel operation delete the row and reset
identity (if necessary) with DBCC CHECKIDENT('[Table Name]', RESEED,
[Identity Seed]) method
Other way is not using the Identity column and manage id column by yourself and it must be clear this approach can't be work in concurrency scenarios.
I think perhaps you're confusing the SQL identity with a ORACLE sequence.
They work completely different.
With the ORACLE sequence you'll get the sequence before you insert the record.
With a SQL Identity, the last identity generated AFTER the insert in available via the SCOPE_IDENTITY() function.
If you really need to show the ID to the user before the insert, your best bet is to keep a counter in a separate table, and read the current value, and increment that by one. As long as "gaps" in the numbers aren't a problem.

Cannot insert the value "Null" into column 'xyz'

I'm having an issue with adding new patients to my SQL database. When I do so, the following error appears, and an SQL Exception is thrown.
Cannot insert the value NULL into column 'ID', table 'IntelliMedDB.dbo.PatientRecord'; column does not allow nulls. INSERT fails.
The information contained in all of the values that are added as parameters aren't actually null. They all have information inside them.
Now, to protect against SQL Injection attacks, all of my queries use parameterized values.
I had an MS Access DB that handled all of this fine (same queries, I've just switched from using OleDBCommand to SqlCommand. Other than that, nothing's changed).
Here's the "INSERT INTO" statement, followed by a parameterized query, just so you all can see what I've done:
INSERT INTO PatientRecord (patientID, firstName, lastName, patientGender, dateOfBirth, residentialAddress, postalAddress, nationalHealthNumber, telephoneNumber, cellphoneNumber)
VALUES (#patientIDNumber, #recepPatFirstName, #recepPatLastName, #recepPatGender, #recepPatDateOfBirth, #recepPatResidentialAddress, #recepPatPostalAddress, #recepNHINumber, #recepPatTelephone, #recepPatCellularNumber)";
(I apologize for the length of the query).
And now, one of the parameterized values:
recepPatRecordCommand.Parameters.AddWithValue("#recepPatFirstName", patRecepFirstName);
Any help gratefully received.
Thank you!
You should edit your question with the definition of the table and the database you are using.
However, the problem is pretty clear. The PatientRecord table has a column called id which is declared to be NOT NULL. That means that NULL values are not allowed -- and you get the error that you see. By not setting a value explicitly in the insert, the value is set to a default. With no default, the value is set to NULL.
Normally, such columns have a default value or are declared to be identity (or auto incrementing).
I think you should probably fix the table so the NOT NULL columns have default values. Or, put in an appropriate value for the id column. For this, you would add id to the column list and then a corresponding value in the values list.
Although your INSERT statement refers to patientId, the error message you are seeing refers to ID.
You are seeing this error because no value for ID is specified.
Open your table in Design
Select your column and go to Column Properties
Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1

Get latest identity, such as ID, from an empty table SQL

I have noticed that SQL keeps track of the latest identity (field it automatically increments each time a new record is created). I want to retrieve the latest identity from the table using C#. Unfortunately most of the time the table is empty (records are written and removed after a while, so often the table is empty).
Is this possible to do this within the bounds of the C# SQL API or do I have to create a stored procedure to retrieve this?
To better explain. If the row above was removed, the next ID number for the next record would be 32. I want to retrieve 32 before the record is written in, in the situation where the table is empty.
SELECT IDENT_CURRENT('table_name')+1;
IDENT_CURRENT returns the last identity value generated for a specific
table in any session and any scope.
http://msdn.microsoft.com/en-us/library/ms175098.aspx
However, although this shows what the next ID will be, this doesn't always mean it will be the next ID entered by yourself. Someone else could INSERT a new record before you.
In short, there is no way of returning the value of what you will next be inserting.
Just in case the increment is not the regular "1":
SELECT IDENT_CURRENT('mytable') + IDENT_INCR('mytable')
Of course, all these rely on the identity column having been populated consistently, ie no messing with manual inserts or reseeding. And Curt has mentioned the possible concurrency issue if you're going to use this ID for your insert directly.
That would be the following query
DBCC CHECKIDENT ('[TableName]', NORESEED )

A member that is computed or generated by the database cannot be changed

I am using LinqToSql as you've seen on subject.
I've a table and some colums in it. There is one colum to show the state of record.
0 : Not approved yet
1 : Approved
2 : Deleted
When the record inserted at first, its value is 0 (default value).
When user approved it its value is changing to 1 but i'm getting this error:
Value of member 'state' of an object of type 'News' changed.
A member that is computed or generated by the database cannot be changed.
This is the test code:
DataClassesDataContext dc = new DataClassesDataContext();
var b = dc.GetTable<Ekler>().Where(p => p.ek_id == 1).FirstOrDefault();
if (b!=null)
{
b.state= "1";
dc.SubmitChanges();
}
What should i do to pass this problem?
You should look at the definition of the "state" column in the designer for the data context, and/or the database itself. Basically LINQ to SQL thinks this is something like an autogenerated value or one which is computed at the database - not something which should be hand-edited. If it should be manually updateable (which it sounds like), you need to tell that to LINQ to SQL.
In my case is my mistake, by accidently I ticked the property - "Auto Generated Value" => True for the field in DBML design mode.
I was facing the same problem when we try to update record in the database. we can insert but when we will try to update records with one of the computed column in the database, it gives an error like : "Value of member of an object of type changed. A member that is computed or generated by the database cannot be changed."
Solution : We cannot update that field in the database but we can edit reference field of the computed column which refers it.When we update reference field then computed column automatically update this field in the table.
Let me know if you have any further query.
Thanks..

Categories

Resources