So I have a column named Timestamp in my database with a default value of GetDate().
Whenever I use Entity Framework to insert a record, Timestamp is null.
Why is this the case?
edit your EDM, make the following change:
Type="datetime"
Nullable="false"
StoreGeneratedPattern ="Computed"
ref:
http://bibby.be/2009/07/entity-framework-sql.html
Try changing type to datetime2. See this article for more information. Also try using Calculated storegeneratedpattern
try changing to datetime2 and then workaround by adding Trigger
SET NOCOUNT ON;
UPDATE ASBLAH
SET YourFieldChangeTime = getdate()
WHERE YOURId IN(SELECT AS_ID FROM INSERTED)
If you need to read data back of this date you can do this after context.SaveChanges()
context.Refresh(System.Data.Objects.RefreshMode.StoreWins, p);
Entity Framework is probably creating an insert statement that includes all fields, with null being the value for Timestamp, since you did not provide one.
If null is allowed for that column, then that is what will be inserted. If null is not allowed, then the default value will be used, which will resolve to GetDate().
Does null need to be allowed for your table?
Related
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
I am using SQLServer 2008, WebForms, C#, Frameowrk 3.5, Entity Framework 1
I generated entity model from DB.
My DB has various tables & lets take example of one table user
It has fields id, name, email, created_on, is_active, is_on_leave
default values for is_active and on_leave properties are default to 0 ( zero ) in db
But When I try to insert a record in this table using entity model, it saves NULL in these fields. How to avoid this? I don't want to set a value for them from my page and want to use the one mentioned in DB.
How can I achieve that?
This columns can be nullable. Right click property in designer, choose properties and set StoreGeneratedPatern for property to computed in the property window.
I found similar question:
Set default value in EF designer datetime
The is_active and is_on_leave columns in your database are nullable. If you make them non-nullable the default values should be used when you do an insert.
ALTER TABLE [user] ALTER COLUMN [is_active] DEFAULT(0) NOT NULL
ALTER TABLE [user] ALTER COLUMN [is_on_leave] DEFAULT(0) NOT NULL
GO
What is the equal code in EntityFramework to this sql code?
select Scope_Identity()
I want to get the id of the last record that i have inserted to database in EF.
You must ensure that your key property is mapped with StoreGeneratedPattern.Identity (here you can find some more about this setting). This should be used as default when generating the model from MS SQL database where the key column is defined with IDENTITY. After that it is enough to call SaveChanges on the context and the key property will be automatically filled for you.
My database table is like this
CREATE TABLE MYBUDGET.tbl_CurrentProperty
(
[PropID] INT NOT NULL IDENTITY(1,1),
[UpdatedOn] DATETIME NOT NULL,
[Amount] MONEY NOT NULL,
[Remarks] VARCHAR(100) NOT NULL,
)
ALTER TABLE MYBUDGET.tbl_CurrentProperty ADD CONSTRAINT PK_CurrentProperty_PropID PRIMARY KEY ([PropID])
ALTER TABLE MYBUDGET.tbl_CurrentProperty ADD CONSTRAINT DF_CurrentProperty_UpdatedOn DEFAULT (DATEADD(MINUTE,30,DATEADD(HOUR, 5, GETUTCDATE()))) FOR [UpdatedOn]
ALTER TABLE MYBUDGET.tbl_CurrentProperty ADD CONSTRAINT CK_CurrentProperty_Amount CHECK([Amount] > -1)
GO
I'm using LINQ to SQL. In C# I need to pass only [Amount] and [Remarks] fields and other fields must be used with their default values ([PropID] and [UpdatedOn]).
In C# I create tbl_CurrentProperties object like below,
tbl_CurrentProperties currentProperties = new tbl_CurrentProperties();
currentProperties.Amount = 50.00M;
currentProperties.Remarks = "remarks";
and then submit the object to the data context. But here, Linq assigned '1/1/0001 12:00:00 AM' for UpdatedOn field. But this violate the SQL datetime range 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM and Occurring an exception. Also I can't assign a NULL value manually for a DateTime field since its a not nullable type. Anyhow I need to make this to use its DEFAULT Constraint. How do I do this?
PS: I want to use it like this because, My database is Online and Users are in different locations. So If I used DateTime.Now, the time in the user machine may be wrong, and It insert a wrong value into DB. I need to use SQL server time always.
Andrey's answer is partly right. I just tested this and here's what I found.
In your dbml designer, on your UpdatedOn column set the following:
Auto Generated Value = True
Nullable = False
Then, on an INSERT if you use SQL Server Profiler to look at the generated SQL, you'll see that UpdatedOn is not included in the INSERT. Not even a null value. This is important: for SQL Server to use a default value for that colum, the column must be omitted from the INSERT. If you set Nullable = True on the UpdatedOn, LINQ to SQL might be including the column on the INSERT with a null value.
FYI, immediately after the INSERT there should be a SELECT where LINQ to SQL is retrieving the auto-generated value, so your entity object has the latest value.
I recommend you open your DBML file using XML Editor and change that column's type from DateTime to DateTime? by allowing nulls. Save it and the code will be generated for you.
Whenever LINQ to SQL generates wrong DBML, it is better to edit it yourself.
Open your dbml and turn on
"Auto Generated Value" = true for the fields that are auto generated. You should be all good with passing nulls in
I'm Developing a small windows application in C#.net in Visual Studio 2010 with framework 3.5. I use LinqToSql for database manipulation.
table name: cprofile
Fields of the table are:
custid int (primary key),
custname varchar(50),
address nvarchar(MAX),
mobileno nchar(10)
So i have changed the 'Is identity' property of the 'cust id' to 'yes'. It automatically changes other 2 sub properties.
Identity Increment = 1
Identity Seed = 1,
After these changes have been made in the table, it throws error when I try to save a new record.
"Cannot insert explicit value for identity column in table 'cprofile'
when IDENTITY_INSERT is set to OFF."
Not too familiar with L2S, but I'd say Daniel is correct: update your model (usually on a context menu somewhere) from the DB. That should prevent it from attempting to insert a value into your auto-incrementing ID column.
I believe there may be a way to have it set IDENTIY_INSERT ON, but I highly recommend against it.
If your table should not be in charge of setting the CustomerId (say, the business has some method of making that determination (especially in a non-linear way), leave your Customer Id column as the PK, but remove the Identity specificaiton from the column.
If you're trying to use the same insert statement you were using before, you can no longer do that. I'm not sure how it's done in the C# side of it, but in SQL, you'd have to run statements to turn identity_insert on, then run your statement. Because you changed the column to identity, the table makes sure the next entry is always 1 number higher than the previous. Because of this, you can't simply insert values into it. If you want the table to create the identity value for you, simply remove it. If my explanation doesn't help, hopefully this will.
Table Definition (Table1)
Col1 Identity
Col2 varchar(50)
Col3 bool
Insert statement before identity
INSERT INTO Table1 VALUES (1, 'Test', TRUE)
Insert statement after identity
INSERT INTO Table1 VALUES ('Test', TRUE)
When identity is on, you cannot specify the value without turning on identity_edit. I'll see if I can find how to do that in Linq.
EDIT: I also like what Daniel said. Didn't think about that.