0

I am refactoring my Database from SQL Queries to Linq.

This function works fine:

public void WriteMessageWithSqlServerTimeOld(string message, string connectionString)
{
    using (var conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (var command = conn.CreateCommand())
        {
            SqlCommandBuilder builder = new SqlCommandBuilder();
            command.CommandText = $"INSERT INTO messages VALUES (GETDATE(), @message);";
            command.Parameters.AddWithValue("@message", message);
            command.ExecuteNonQuery();
        }
    }
}

But i would like to know how you could write this with linq. My naive attempt looked like this:

public void WriteMessageWithSqlServerTimeNew(string message, string connectionString)
{
    var db = new DataContext(connectionString);
    var messages = db.GetTable<MessageEntityClass>();
    var message = new MessageEntityClass()
    {
        Message = message, ServerTime = System.Data.Objects.SqlClient.SqlFunctions.GetDate()
    };
    messages.InsertOnSubmit(message);
    db.SubmitChanges();
}

But this gives me a

System.NotSupportedException: 'This function can only be called from 'LINQ to Entities'.'

Essentially my Question is, how can I call System.Data.Objects.SqlClient.SqlFunctions.GetDate() (or any other sql function) When inserting data into the database?

1 Answer 1

1

You should use the basic .NET method, DateTime.Now.

It translates to SQL as GetDate().

Your code :

var message = new MessageEntityClass()
{
    Message = message, ServerTime = DateTime.Now
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but that does not achieve what i intended. I want the datetime of the sql-server, this gives me the datetime of the client.

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.