VS 2010 .net 4.0에서 엔티티 프레임 워크를 사용할 때 'datetime2'오류
이 오류가 발생합니다.
System.Data.SqlClient.SqlException : datetime2 데이터 형식을 datetime 데이터 형식으로 변환하면 값이 범위를 벗어났습니다.
내 엔티티 객체는 모두 DB 객체에 정렬됩니다.
Google을 통해이 오류에 대한 참조를 하나만 찾았습니다.
이것을 읽은 후, 나는 우리가 기억 한 2 필드를 추가하고 나는 확실히 그 차이를 "코딩 손"에 의해 무엇을 의미하는지 모르겠어요 VS 2010에서 개체 모델을 업데이트했습니다. 나는 아무것도 보이지 않는다.
내가 코드에서하는 일은 엔티티 객체를 채운 다음 저장하는 것뿐입니다. (또한 코드에서 새 필드를 채 웁니다.) 날짜 필드를 DateTime.Now
..
코드의 중요한 부분은 다음과 같습니다. ctx.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
데이터베이스는 SQL Server 2008입니다.
생각?
나머지 오류 :
System.Data.Mapping.Update.Internal.UpdateTranslator.Update (IEntityStateManager stateManager, IEntityAdapter adapter)의 System.Data.EntityClient.EntityAdapter.Update (IEntityStateManager entityCache)의 System.Data.Objects.ObjectContext.SaveChanges (SaveOptions options) SpeciesPost.svc.cs의 SafariAdmin.Site.WebServices.SpeciesPost.SaveOrUpdateSpecies (String sid, String fieldName, String authToken) : SafariAdmin.TestHarness.Tests.Site.WebServices.SpeciesPostSVC_Tester.SaveNewSpecies ()의 58 행 SpeciesPostSVC_Tester.cs : 행 33-System.Data.SqlClient.SqlConnection.OnError (SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError (SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ()의 SqlException System.Data.SqlClient.TdsParser에서.Run (RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData () at System.Data () at System.Data.SqlClient.SqlDataReader.get_Meta. FinishExecuteReader (SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds (CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data. , Boolean returnStream, String 메서드, DbAsyncResult 결과) at System.Data.SqlClient.SqlCommand.RunExecuteReader (CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader (CommandBehavior 동작, String 메서드)의 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader (CommandBehavior 동작)의 System.Data.Common.DbCommand.ExecuteReader (CommandBehavior 동작)의 System.Data.Mapping.Update.Internal .DynamicUpdateCommand.Execute (UpdateTranslator 변환기, EntityConnection 연결, 사전
2 identifierValues, List
System.Data.Mapping.Update.Internal.UpdateTranslator.Update (IEntityStateManager stateManager, IEntityAdapter 어댑터)에서 1 generatedValues)
엔티티 프레임 워크는 모든 날짜를 Datetime2로 처리하므로 데이터베이스의 필드가 Datetime 인 경우 문제가 될 수 있습니다. 여기서도 동일한 문제가 발생했으며 모든 날짜 필드를 채우고 데이터 유형을 변경하는 것이 가장 일반적인 솔루션입니다.
Code First를 사용하는 경우 선택적 DateTime
속성을 DateTime?
또는 로 선언해야합니다 Nullable<DateTime>
. 설정되지 않은 DateTime
개체는 문제를 일으킬 수 있습니다.
속성이 데이터베이스에서 nullable이고 DateTime
코드 의 표준 (아님 DateTime?
) 인 경우 ADO.NET은 0001-01-01 (아님 NULL
) 날짜를 사용하여 삽입 명령을 보내지 만 최소 SQL DateTime 값은 1753-01-01입니다. , 오류가 발생합니다. DateTime
코드 의 속성이 nullable (예 : DateTime?
또는 Nullable<DateTime>
) 인 경우 insert 명령은 NULL
범위를 벗어난 날짜 대신 삽입을 시도 합니다.
해당 SQL 스크립트를 사용하여 모든 열을 datetime에서 datetime2
. 편의를 위해 'aspnet'이 포함 된 모든 테이블을 건너 뜁니다.
DECLARE @SQL AS NVARCHAR(1024)
DECLARE @TBL AS NVARCHAR(255)
DECLARE @COL AS NVARCHAR(255)
DECLARE @NUL AS BIT
DECLARE CUR CURSOR FAST_FORWARD FOR
SELECT SCHEMA_NAME(t.schema_id)+'.'+t.name, c.name, c.is_nullable
FROM sys.tables AS t
JOIN sys.columns c ON t.object_id = c.object_id
JOIN information_schema.columns i ON i.TABLE_NAME = t.name
AND i.COLUMN_NAME = c.name
WHERE i.data_type = 'datetime' and t.name not like '%aspnet%'
ORDER BY t.name, c.name
OPEN CUR
FETCH NEXT FROM CUR INTO @TBL, @COL, @NUL
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @SQL = 'ALTER TABLE ' + @TBL
+ ' ALTER COLUMN [' + @COL + '] datetime2'
+ (CASE WHEN @NUL=1 THEN '' ELSE ' NOT' END) + ' NULL;'
EXEC sp_executesql @SQL
FETCH NEXT FROM CUR INTO @TBL, @COL, @NUL
END
CLOSE CUR;
DEALLOCATE CUR;
그것은 나를 위해 작동합니다!
또 다른 가능한 해결책은 필드의 SQL 열 유형을 datetime2로 설정하는 것입니다. 이는 fluentapi를 사용하여 수행 할 수 있습니다.
Property(x => x.TheDateTimeField)
.HasColumnType("datetime2");
참고 : SQL Server 2005 이하에서는 datetime2를 사용할 수 없으므로이 솔루션은 SQL Server 2008 이상을위한 솔루션입니다.
I had the same problem and solve it by put the [Column(TypeName = "datetime2")]
attribute to related properties, like below sample:
[Column(TypeName = "datetime2")]
public DateTime? PropertyName { get; set; }
I know that it's an old question, but as I googled here, someone else could do the same ;-) For ones that changing from DateTime to DateTime2 isn't an option (as for SQL2005 users), I think that in most cases is more reasonable to populate fields left empty with something like (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue
and not with DateTime.now, as it's easier to recognize it as a "pseudo-null" value (and if it's needed convert it to a real null in a partial class of father object)
When using Entity framework code first, declare it like this:
public Nullable<System.DateTime> LastLogin { get; set; }
Is there ModifiedTime property in your entity, which is updated on the database side only? If so, you must use DatabaseGeneratedOption.Computed (for EF CodeFirst). Also visit this https://stackoverflow.com/a/9508312/1317263
Thank you.
We had the same issue. This was related to the mssql version. We made it works on all of our version with this method.
Open your edmx file with an xml editor Find this line on the top of your file
<Schema Namespace="XXXXX.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008"
Replace the 2008 by 2005 Save your file, recompile the project.
Hope that will help someone else in the futur.
I only tried this solution with a dbfirst approche.
Whatever fits in a datetime will fit in a datetime2 data type, vice versa this is not the case, you can stick a date of January 1500 in a datetime2 data type but datetime only goes back to 1753, a datetime2 column can go back all the way to the year 1. I would check what the min date that you are passing in is and if your tables have datetime2 or datetime data type columns
After trying to solve this issue for several days I used DateTime?
as the datatype in my model with Entity Framework Code-First instead of DateTime
.
Ensure that none of the not null fields in the DB(datetime) are left out while inserting/updating. I had the same error and on inserting values to those datetime fields the issue was solved.This occurs if the not null datetime fields are not assigned a proper value.
I had the same issue in my ASP.Net MVC application.
There were two model classes in my application that had DateTime properties.
upon investigating I noticed that the DateTime property of one model was nullable i.e. to make it date of Birth optional property
the other model had DateTime Property with Required data annotation (error occurs when saving this model)
my app is code first so I resolved the issue by setting datatype as DateTime2
[Column(TypeName="datetime2")]
then I ran the migration on package manager console.
Simple. On your code first, set the type of DateTime to DateTime?. So you can work with nullable DateTime type in database.
This follows on from stepanZ answer... I got this error when using Entity Framework Code First
with AutoMapper
.
When setting up the AutoMapping
we have createddt
, updateddt
, createdby
and updatedby
fields which are automatically set in our public override int SaveChanges()
function. When doing this you need to ensure you set these fields to be ignored by AutoMapper
, otherwise the database will get updated with null
for those fields when they are not supplied from the View
.
My issue was that I had put the source and destination around the wrong way, therefore trying to ignore the fields when setting the ViewModel
, instead of when setting the Model
.
The Mapping
looked like this when I recieved this error (note: the cfg.CreateMap<Source, Destination>()
on the second line is mapping the Model
to the ViewModel
and setting the Ignore()
)
cfg.CreateMap<EventViewModel, Event>();
cfg.CreateMap<Event, EventViewModel>()
.ForMember(dest => dest.CreatedBy, opt => opt.Ignore())
.ForMember(dest => dest.CreatedDt, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedBy, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedDt, opt => opt.Ignore());
The source and destination should be ignored for a mapping from ViewModel
To Model
(note: The code below is correct where the Ignore()
is placed against the mapping for the ViewModel
to the Model
)
cfg.CreateMap<Event, EventViewModel>();
cfg.CreateMap<EventViewModel, Event>()
.ForMember(dest => dest.CreatedBy, opt => opt.Ignore())
.ForMember(dest => dest.CreatedDt, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedBy, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedDt, opt => opt.Ignore());
Two solutions:
Declare the properties in your class like below and make an update-database:
public DateTime? MyDate {get; set;}
Or set a date for the property in the Seed method that populates the database, no need of update-database :
context.MyClass.AddOrUpdate(y => y.MyName,new MyClass { MyName = "Random", MyDate= DateTime.Now })
'program tip' 카테고리의 다른 글
설치된 Drupal 버전을 찾는 방법 (0) | 2020.12.03 |
---|---|
NSLocalizedString에서 변수 및 / 또는 매개 변수를 사용할 수 있습니까? (0) | 2020.12.03 |
FormData로 업로드 된 Blob에 파일 이름을 지정하는 방법은 무엇입니까? (0) | 2020.12.03 |
자바 : for (;;) 대 while (true) (0) | 2020.12.03 |
치명적 오류 : 부울에서 멤버 함수 bind_param () 호출 (0) | 2020.12.03 |