Entity Model - How to use Database's Default Column Values while inserting - c#

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

Related

Enforce Entity Framework to follow constraints defined in database

I have a table with 10 columns, in which 7 of them are not null with constraints on it.
ALTER TABLE [dbo].[MyTable]
ADD DEFAULT (1) FOR [Column1]
Now, when I am inserting 3 columns from Entity Framework like below, it is not inserting the default values into the table:
Table obj1 = new Table();
obj1.Column7 = someValue;
obj1.column8 = someValue;
obj1.column9 = someValue;
context.Entry(obj1).State = EntityState.Added;
context.SaveChanges();
Unlike my expectation, above statement is just updating 3 columns and not using the default values for the other 7 columns.
How can I enforce Entity Framework to insert default values defined by the constraint in database?
The default values as defined in your SQL Server table structure are only applied if you have an INSERT statement that leaves out those columns - e.g. doesn't provide any value (including NULL) for those columns.
EF however will always supply values for all columns as defined by the entity - e.g. it will supply NULL for any values not explicitly set. There's nothing you can do about this, as far as I know.
There are some workarounds:
you could create a stored procedure which would take only those values you want to supply, and would run a SQL INSERT statement that would leave out the columns with default values, e.g.
INSERT INTO dbo.MyTable (colA, colB, ..., colZ) -- *exclude* "Column1" here!
VALUES ( .........)
With this, SQL Server would then use the configured default values for those column that have one defined and which are not mentioned in the column list of the INSERT INTO statement
you could probably do something similar on the EF level, by specifying a second class, that would be almost identical to your current entity class - but that would leave out the columns you want to have set by SQL Server's configured default values. If you save this "slimmed down" entity, EF would create a SQL statement that would include only those columns that it knows about (in terms of the fields of that slimmed down class) and this would result basically in the same as above - an INSERT INTO statement that excludes those columns which are automatically set by a configured SQL Server default constraint

Binding source tries to update identity

I set up a normal binding source with a datagridview to a table. I also set the ID to identity so that I wouldn't have to worry about it. But whenever I call .UpdateAll() on the BindingSource I get the SQL Exception
"Cannot insert explicit value for identity column in table 'Teachers'
when IDENTITY_INSERT is set to OFF."
Now how do I tell the binding Source NOT to push the empty ID column to the table? I know this seems like an issue that was already discussed a hundred times before, but I'm new to this and it's driving me crazy.
Depending on what you want to achieve there is a couple of approach. If you want your identity column to contain non-unique values (which isn't very good idea, but the decision is yours to make) then you can simply disable the identity column in the database:
SET IDENTITY_INSERT Teachers ON;
To revert it run the following:
SET IDENTITY_INSERT Teachers OFF;
But probably, what makes more sense is to make your identity column autoincrement. So when designing your Teachers table the ID column should have this form:
[ID] [int] IDENTITY(1,1) NOT NULL
Or, if you are using SQL Server Management Studio:
Go to your table. Right click it and select Design.
Select the ID column.
In column properties tab find "Identity Specification".
Set "Is Identity" to "Yes", "Identity Increment" to "1", "Identity Seed" to "1".
That should make your ID column to increase automatically hence avoiding empty value when updating the data from the DataGridView.

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

getdate() not working with Entity Framework

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?

Violation of PRIMARY KEY constraint Cannot insert duplicate key in object . In C#.net....Visual Studio 2010...framework 3.5

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.

Categories

Resources