0

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Assuming 1. You have a default value because you don't ever want to have null in those columns, and 2. You have control over the database, it seems sensible to make the columns non-nullable. If either of those assumptions are incorrect, this is a good workaround :)
I agree with the first assumption - if you set default, you do not want null in columns, but I disagree with that my solution is a workaround - he MUST set StoreGeneratedPattern even if he alter column and make it not nullable. If he only set not null in the db level, and not set storegeneratedpattern, he will receive an error because of the insertion of null value in the column that not allow null.
If you set the column to non-nullable then update your model from the database, the property corresponding to the database field will be non-nullable and the EF will insert the default value of the property type, not null. In this case the default value of the property type is false, which is also the default value in the database. I'd say setting storegeneratedpattern cures the problem, but making the columns non-nullable prevents it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.