M
M
Maxim2018-10-13 23:33:51
SQL
Maxim, 2018-10-13 23:33:51

Convert DateTime to DateTime?

Model

public class Author
    {
        [Display(Name = "Author")] //Set names on Views
        public Int32 Id { get; set; }
        [Display(Name = "Author's name")] //Set names on Views
        public String Name { get; set; }
        [DataType(DataType.Date)] //Only date in this field
        public DateTime Birthday { get; set; }
        [DataType(DataType.Date)] //Only date in this field
        public DateTime Death { get; set; }

        public IEnumerable<Book> Books { get; set; }
    }

Autogenerated method
// POST: api/AuthorsApi
        [ResponseType(typeof(Author))]
        public IHttpActionResult PostAuthor(Author author)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Это добавил, но не помогло
            author.Birthday = author.Birthday.Date;
            author.Death = author.Death.Date;

            db.Authors.Add(author);
            db.SaveChanges();   // ************** ТУТ ОШИБКА *****************

            return CreatedAtRoute("DefaultApi", new { id = author.Id }, author);
        }

A little more if needed

Автосгенерированная таблица
CREATE TABLE [dbo].[Authors] (
    [Id]       INT            IDENTITY (1, 1) NOT NULL,
    [Name]     NVARCHAR (MAX) NULL,
    [Birthday] DATETIME       NOT NULL,
    [Death]    DATETIME       NOT NULL,
    CONSTRAINT [PK_dbo.Authors] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Запрос
User-Agent: Fiddler
Host: localhost:62498
Content-Type: application/json
Content-Length: 69
{"id":"0", name:"aka", "Birthday":"01.02.1234", "death":"12.11.1098"}


Mistake
SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

I realized that the types do not want to meet each other.
How to fix it so that the database and the Model are not touched?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir S, 2018-10-14
@Got_Oxidus

you most likely have a value / I author.Birthday; author.Death;less than 01/01/1753 another
link

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question