Linq To Sql : SQL Default Value overridden - sql-server

I have read several post around the problem but found not solution to the issue I'm facing with.
My entity model contains several date properties whose values I need to be set at SQL server level. Here's an example:
[Column(IsDbGenerated = true)]
public DateTime DateCreated { get; set; }
DateCreated is a 'date' type on SQL Server, and its default value is GETDATE().
[DateCreated] DATE DEFAULT (getdate()) NOT NULL,
As a matter of fact saving a new record (without passing any DateCreated value) results in '1/1/0001' (i.e. null datetime) value being inserted.
It looks like Linq overrides default server GETDATE() value, forcing a 'null' value to be written.

You must use DatabaseGenerationOption.Identity.
Here are two links that explain further:
Entity Framework Code First Data Annotations
How do I tell Entity Framework to allow SQL Server to provide a defined default value for a field?

Related

HSQLDB inserting datetime format for SQL Server throws exception

I am trying to run unit tests for my SQL Server query. Query is simply inserting date to the table. I tried two different formats but didn't work:
parameters.addValue(STUDY_DATE, getDate(studyEvent.getStudy().getStudyDate()));
Timestamp timestamp = new Timestamp(getDate(studyEvent.getStudy().getStudyDate()).getTimeInMillis());
parameters.addValue(STUDY_DATE, timestamp);
And this is getDate() method that returns Calendar object:
private Calendar getDate(long time) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
calendar.setTimeInMillis(time);
return calendar;
}
I am not sure if the problem is that SQL Server's datetime format issue or hsqldb issue. Here is my hsqldb create table:
SET DATABASE SQL SYNTAX MSS TRUE;
DROP TABLE event_study IF EXISTS;
CREATE TABLE event_study
(
STUDY_ID INT,
STUDY_DATE DATE
)
Is my hsqldb setup wrong? or should I use different datetime format for SQL Server?
Error I am getting is:
data exception: invalid datetime format; nested exception is java.sql.SQLDataException: data exception: invalid datetime format
and SQL query that I am running is:
INSERT INTO event_study(study_id, study_date)
SELECT x.*
FROM (VALUES(:study_id, :study_date))
AS x(study_id, study_date)
WHERE NOT EXISTS (SELECT 1 FROM event_study s WHERE s.study_id = x.study_id)
As you are not using strings for dates, this is not actually a formatting issue, but a Java type issue. With your table definition, DATE does not have time information. You can create and use a java.sql.Date object for the parameter value. If you want a datetime column, which includes information on time of the day, then use TIMESTAMP in your table definition and a java.sql.Timestamp for the parameter value.
In either case, you cannot use a Calendar object as parameter value.

How to select specified columns and its values from SQL Server stored procedure result and convert them into JSON?

I am new to SQL Server. Here are my requirements:
Requirements:
I need to select specified column header and its values from SQL Server stored procedure result
The selected column header and its values are serialize into a JSON string object in SQL Server 2012
What I did:
I need to monitor the table data changes in SQL Server Management Studio 2012. If any insert, delete and updates occur in the old table data, I need to send instant messages from SQL Server to a WCF service.
To send instant messages, first of all, I need to select specified columns from the result set of a stored procedure, and serialize them as a JSON string.
I am followed Change Data Capture feature in database and its table for tracking table data changes.
For the above, I created a database and table with Change Data Capture feature enabled. Then I inserted values in table data.
At last, using the stored procedure, I view the table data changes as result.
My demo query:
DECLARE #from_lsn binary(10), #to_lsn binary(10)
SET #from_lsn = sys.fn_cdc_get_min_lsn('dbo_one')
SET #to_lsn = sys.fn_cdc_get_max_lsn()
SELECT
CT.__$start_lsn, CT.__$operation,
CASE CT.__$operation
WHEN 1 THEN 'Delete'
WHEN 2 THEN 'Insert'
WHEN 3 THEN 'Update - Pre'
WHEN 4 THEN 'Update - Post'
END AS Operation,
CT.*,
LSN.tran_begin_time, LSN.tran_end_time, LSN.tran_id
FROM
cdc.fn_cdc_get_all_changes_dbo_one (#from_lsn, #to_lsn, N'all update old') AS CT
INNER JOIN
cdc.lsn_time_mapping AS LSN ON CT.__$start_lsn = LSN.start_lsn
From the above result, I need to select the type of operation, changed column header and its values.
After selecting, I need to serialize them all as a JSON string, then pass the JSON object from SQL Server 2012 to a WCF service via a POST method.
How can I achieve this? Could anyone help me solve this?
Actually it's simple. First you need to create an object like this:
[DataContract]
public class Output
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string ID { get; set; }
.
.
.
//all other parameters
}
Then put your stored procedure output into it. That's all. Then just return it with WCF service.

Should I use the Date or DateTime SqlDbType when adding a DateTime C# value for a Date SQL Server field?

I've got a table with a field of Date data type. Although I would expect just the raw date in that field when inserting a value into it like so:
update reportsgenerated
set begindate = '2016-02-01'
where rptgenid = 2;
...it actually sems to store a date time value, as it is represented in LINQPad as "2/1/2016 12:00:00 AM".
The C# value I'm assigning to the parameter when inserting is a DateTime type (as C# doesn't have a "Date"-only type):
DateTime begDate = // bla
That being the case, should I designate the parameter as a Date type, to match the table:
insertRptsGenerated.Parameters.Add("#BeginDate", SqlDbType.Date).Value = begDate;
...or as a DateTime type, to match the assigned value's type:
insertRptsGenerated.Parameters.Add("#BeginDate", SqlDbType.DateTime).Value = begDate;
?
.NET already knows what type it is in .NET. You are being asked what type to use on the other end, hence the SqlDb part of the SqlDbType ;-). You should match, as closely as possible, the type of the parameter on the database side.
For the complete list of mappings, please see the MSDN page for SQL Server Data Type Mappings.
That chart shows:
SQL Server DATE == .NET DateTime == SqlDbType.Date

CURRENT_TIMESTAMP defaults to "null" value, possible reasons?

So if I run a virtual instance of IIS on localhost to test some site, I have a datebase field with a default CURRENT_TIMESTAMP that upon insertion always defaults to 1/1/0001 12:00:00 AM, which is, as I understand, the null-like value for DateTime in these scenarios.
Why is this happening? Can't I get the actual time and date to go in this field?
I've tried using getdate(), sysdatetime() and whichever else alternatives and it's the same thing.
The field in the C# code is:
public DateTime LastModification { get; set; }
Any workaround around this?
I'm using the correct mappings as per msdn

MVC 3 date created and modified have default values and triggers in SQL Server 2008 R2, but still want value

I have generated classes (DbContext) modelling my db (SQL Server 2008 R2), and in most of my tables I have the standard ModifiedDate and CreatedDate (No Nulls). Each of these has a default of getdate() in SQLServer, and I have a trigger to update ModifiedDate on any updates.
The generated views included the ModifiedDate and CreatedDate fields, which I don't want (the user shouldn't see these), so I've taken these out, but when adding a new entry using the generated Create view, I get the error "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value".
I then added some default values, and it did add the record, but naturally it added my entered values, and not the SQL getdate() values, which I'd prefer (I want it to show the server time). Checking the object (db.SaveChanges()) the fields have a value of {1/01/0001 12:00:00 AM}.
How can I use these models without entering dates??? I've searched but haven't found my answer... ;-(
This is a common problem in both Entity Framework and Linq to SQL:
In Linq-To-SQL the model doesn't know about the default values, and so attempts to assign them as "null" - which in this case isn't acceptable. To fix this, open the DBML file and set the "Auto Generated Value" option to "true" for the fields in question.
In Entity Framework it's a little different: you set the "StoreGeneratedPattern" on the field to either "Identity" or "Computed". Here's the description:
http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.storegeneratedpattern.aspx
EF will do this automatically for Identity type fields, but not for default value/not null fields. You may want to set your CreatedDate as "Identity" (updated only on insert) and your ModifiedDate as "Computed" (updated on insert and update).
The byproduct of this is that you then will not be able to set the fields via Linq at all - but that's fine in your use case, I think.

Resources