datetime2 데이터 유형을 datetime 데이터 유형으로 변환하면 범위를 벗어난 값이 발생했습니다.
내 HomeController에 다음 코드가 있습니다.
public ActionResult Edit(int id)
{
var ArticleToEdit = (from m in _db.ArticleSet where m.storyId == id select m).First();
return View(ArticleToEdit);
}
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Article ArticleToEdit)
{
var originalArticle = (from m in _db.ArticleSet where m.storyId == ArticleToEdit.storyId select m).First();
if (!ModelState.IsValid)
return View(originalArticle);
_db.ApplyPropertyChanges(originalArticle.EntityKey.EntitySetName, ArticleToEdit);
_db.SaveChanges();
return RedirectToAction("Index");
}
그리고 이것은 Edit 메소드의 뷰입니다.
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="headline">Headline</label>
<%= Html.TextBox("headline") %>
</p>
<p>
<label for="story">Story <span>( HTML Allowed )</span></label>
<%= Html.TextArea("story") %>
</p>
<p>
<label for="image">Image URL</label>
<%= Html.TextBox("image") %>
</p>
<p>
<input type="submit" value="Post" />
</p>
</fieldset>
<% } %>
제출 버튼을 누르면 오류가 발생합니다. {"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."}
문제가 무엇인지 아십니까? 편집 방법이 DB에 게시 된 값을 편집 된 것으로 업데이트하려고한다고 가정하지만 어떤 이유로 든 좋아하지는 않습니다 ... 나는 날짜에 언급되지 않은 날짜가 왜 관련되어 있는지 알지 못하지만 편집 컨트롤러 방법?
문제는 ApplyPropertyChanges
양식 (헤드 라인, 스토리 및 이미지)의 데이터로만 채워진 모델 객체와 함께 사용한다는 것 입니다. ApplyPropertyChanges
초기화되지 않은을 포함하여 개체의 모든 속성에 변경 사항을 적용합니다.이 속성 DateTime
은 SQL Server의 범위를 벗어난 0001-01-01로 설정되어 DATETIME
있습니다.
을 사용하는 대신 ApplyPropertyChanges
수정중인 객체를 검색하고 양식을 편집하는 특정 필드를 변경 한 다음 수정 사항으로 객체를 저장하는 것이 좋습니다. 이렇게하면 변경된 필드 만 수정됩니다. 다른 방법으로 채워진 다른 필드를 사용하여 페이지에 숨겨진 입력을 넣을 수는 있지만 동시 편집에는 적합하지 않습니다.
최신 정보:
다음은 객체의 일부 필드를 업데이트 한 테스트되지 않은 샘플입니다 (LINQ to SQL을 사용한다고 가정합니다).
var story = _db.ArticleSet.First(a => a.storyId == ArticleToEdit.storyId);
story.headline = ArticleToEdit.headline;
story.story = ArticleToEdit.story;
story.image = ArticleToEdit.image;
story.modifiedDate = DateTime.Now;
_db.SubmitChanges();
이것은 Entity Framework를 사용할 때 사람들이 겪는 일반적인 오류입니다. 이는 저장중인 테이블과 연관된 엔티티에 필수 날짜 시간 필드가 있고 일부 값으로 설정하지 않은 경우 발생합니다.
기본 날짜 / 시간 객체는 값으로 만들어지며 01/01/1000
null 대신 사용됩니다. 날짜 / 시간 1753-01-01 00:00:00
이후 날짜 값을 보유 할 수있는 datetime 열로 전송되며 범위를 벗어난 예외가 발생합니다.
이 오류는 null을 허용하도록 데이터베이스 필드를 수정하거나 값으로 필드를 초기화하여 해결할 수 있습니다.
DATETIME
1753/1/1부터 "영원"까지 (9999/12/31),DATETIME2
0001/1/1부터 영원까지 지원합니다.
Answer: I suppose you try to save DateTime
with '0001/1/1' value. Just set breakpoint and debug it, if so then replace DateTime
with null
or set normal date.
This one was driving me crazy. I wanted to avoid using a nullable date time (DateTime?
). I didn't have the option of using SQL 2008's datetime2 type either (modelBuilder.Entity<MyEntity>().Property(e => e.MyDateColumn).HasColumnType("datetime2");
).
I eventually opted for the following:
public class MyDb : DbContext
{
public override int SaveChanges()
{
UpdateDates();
return base.SaveChanges();
}
private void UpdateDates()
{
foreach (var change in ChangeTracker.Entries<MyEntityBaseClass>())
{
var values = change.CurrentValues;
foreach (var name in values.PropertyNames)
{
var value = values[name];
if (value is DateTime)
{
var date = (DateTime)value;
if (date < SqlDateTime.MinValue.Value)
{
values[name] = SqlDateTime.MinValue.Value;
}
else if (date > SqlDateTime.MaxValue.Value)
{
values[name] = SqlDateTime.MaxValue.Value;
}
}
}
}
}
}
You can also fix this problem by adding to model (Entity Framework version >= 5)
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreationDate { get; set; }
If you have a column that is datetime and allows null you will get this error. I recommend setting a value to pass to the object before .SaveChanges();
I got this error after I changed my model (code first) as follows:
public DateTime? DateCreated
to
public DateTime DateCreated
Present rows with null-value in DateCreated caused this error. So I had to use SQL UPDATE Statement manually for initializing the field with a standard value.
Another solution could be a specifying of the default value for the filed.
In my case, in the initializer from the class I was using in the database's table, I wasn't setting any default value to my DateTime property, therefore resulting in the problem explained in @Andrew Orsich' answer. So I just made the property nullable. Or I could also have given it DateTime.Now in the constructor. Hope it helps someone.
It looks like you are using entity framework. My solution was to switch all datetime columns to datetime2, and use datetime2 for any new columns, in other words make EF use datetime2 by default. Add this to the OnModelCreating method on your context:
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
That will get all the DateTime and DateTime? properties on all the entities in your model.
If you are using Entity Framework version >= 5 then applying the [DatabaseGenerated(DatabaseGeneratedOption.Computed)] annotation to your DateTime properties of your class will allow the database table's trigger to do its job of entering dates for record creation and record updating without causing your Entity Framework code to gag.
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime DateCreated { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime DateUpdated { get; set; }
This is similar to the 6th answer, written by Dongolo Jeno and Edited by Gille Q.
Also, if you don't know part of code where error occured, you can profile "bad" sql execution using sql profiler integrated to mssql.
Bad datetime param will displayed something like that :
I had the same problem, unfortunately, I have two DateTime property on my model and one DateTime property is null before I do SaveChanges.
So make sure your model has DateTime value before saving changes or make it nullable to prevent error:
public DateTime DateAdded { get; set; } //This DateTime always has a value before persisting to the database.
public DateTime ReleaseDate { get; set; } //I forgot that this property doesn't have to have DateTime, so it will trigger an error
So this solves my problem, its a matter of making sure your model date is correct before persisting to the database:
public DateTime DateAdded { get; set; }
public DateTime? ReleaseDate { get; set; }
This problem usually occurs when you are trying to update an entity. For example you have an entity that contains a field called DateCreated
which is [Required] and when you insert record, no error is returned but when you want to Update that particular entity, you the get the
datetime2 conversion out of range error.
Now here is the solution:
On your edit view, i.e. edit.cshtml
for MVC users all you need to do is add a hidden form field for your DateCreated
just below the hidden field for the primary key of the edit data.
Example:
@Html.HiddenFor(model => model.DateCreated)
Adding this to your edit view, you'll never have that error I assure you.
Try making your property nullable.
public DateTime? Time{ get; set; }
Worked for me.
If you ahve access to the DB, you can change the DB column type from datetime to datetime2(7) it will still send a datetime object and it will be saved
The model should have nullable datetime. The earlier suggested method of retrieving the object that has to be modified should be used instead of the ApplyPropertyChanges. In my case I had this method to Save my object:
public ActionResult Save(QCFeedbackViewModel item)
And then in service, I retrieve using:
RETURNED = item.RETURNED.HasValue ? Convert.ToDateTime(item.RETURNED) : (DateTime?)null
The full code of service is as below:
var add = new QC_LOG_FEEDBACK()
{
QCLOG_ID = item.QCLOG_ID,
PRE_QC_FEEDBACK = item.PRE_QC_FEEDBACK,
RETURNED = item.RETURNED.HasValue ? Convert.ToDateTime(item.RETURNED) : (DateTime?)null,
PRE_QC_RETURN = item.PRE_QC_RETURN.HasValue ? Convert.ToDateTime(item.PRE_QC_RETURN) : (DateTime?)null,
FEEDBACK_APPROVED = item.FEEDBACK_APPROVED,
QC_COMMENTS = item.QC_COMMENTS,
FEEDBACK = item.FEEDBACK
};
_context.QC_LOG_FEEDBACK.Add(add);
_context.SaveChanges();
[Solved] In Entity Framework Code First (my case) just changing DateTime
to DateTime?
solve my problem.
/*from*/ public DateTime SubmitDate { get; set; }
/*to */ public DateTime? SubmitDate { get; set; }
Error: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
This error occurred when due to NOT assigning any value against a NOT NULL date column in SQL DB using EF and was resolved by assigning the same.
Hope this helps!
Got this problem when created my classes from Database First approach. Solved in using simply Convert.DateTime(dateCausingProblem) In fact, always try to convert values before passing, It saves you from unexpected values.
You have to enable null value for your date variable :
public Nullable<DateTime> MyDate{ get; set; }
'development' 카테고리의 다른 글
jQuery를 사용하여 iPad 사용자를 감지 하시겠습니까? (0) | 2020.05.29 |
---|---|
클릭시 href 이미지 링크 다운로드 (0) | 2020.05.29 |
문자 수를 10으로 제한하는 정규식 (0) | 2020.05.29 |
Bash 스크립트에 전달 된 인수 수를 어떻게 찾습니까? (0) | 2020.05.29 |
C # 코드에서 .NET 4.0 튜플을 사용하는 것이 좋지 않은 디자인 결정입니까? (0) | 2020.05.28 |