2014-09-08 2 views
0

아래와 같이 Entity Framework 스키마가 있습니다.Entity Framework에서 DateTime과 문자열을 비교하는 방법

Class Contact 
{ 
    string name; 
    DateTime creationDate; 
} 
and i've a string that is 

string date="9/9/14 3:00:00 PM" 

난 foll0wing 쿼리

var q=from u in db.Contacts where u.creationDate.ToString==date select u; 

을 실행하고 있지만있어서 '선택 System.String ToString() 메소드를 인식하지 않는 엔티티 다음 오류를

LINQ 대향하고,이 메서드를 저장소 식으로 변환 할 수 없습니다.

어느 날 내가 dateTime과 string을 어떻게 비교할 수 있습니까? 가능한 캐스팅은 무엇입니까? 같은

+0

문자열을 DateTime 개체로 구문 분석하고 쿼리에서 사용하십시오. –

+0

예이 문을 통해 수행 한 DateTime temp = Convert.ToDateTime (date); 이제 쿼리 결과가 반환되지 않습니다. – DonetDeveloper

답변

0

뭔가 다음

var date = DateTime.Parse("9/9/14 3:00:00 PM"); 

var q from u in db.Contacts 
     where u.creationDate == date 
     select u; 
+0

데이터베이스에 "9/9/14 3:00:00 PM"이 존재하지만 어떤 결과도 반환하지 않습니다. – DonetDeveloper

+0

날짜가 정확하게 구문 분석되고 있습니까? ParseExact를 사용하여 'DateTime.ParseExact ("9/9/14 3:00:00 PM", "M/d/yy h : 00 : ss tt", System.Globalization.CultureInfo.InvariantCulture)' – rmorrin

+0

내가 당신의 방법을 통해 구문 분석 할 때 다음 오류가 발생했습니다. "유효한 DateTime으로 문자열이 인식되지 않았습니다." – DonetDeveloper

1

Change your string to a DateTime 같은 것을 (새 날짜 시간() 실 거예요 작업로 .toString()가 작동하지 않는 것과 같은 이유, 즉 엔티티 프레임 워크는 그것을 알고하지 않습니다 중 하나) :

[EdmFunctionAttribute("Edm", "CreateDateTime")] 
public static Nullable<DateTime> CreateDateTime(
    Nullable<int> year, 
    Nullable<int> month, 
    Nullable<int> day, 
    Nullable<int> hour, 
    Nullable<int> minute, 
    Nullable<double> second 
) 

매개 변수

년 유형 : 선택 System.Nullable를

The year part of the new date. 

개월 유형 : 선택 System.Nullable

The month part of the new date. 

일 유형 : 선택 System.Nullable

The day part of the new date. 

시간 유형 : 선택 System.Nullable

The hour part of the new date. 

분 유형 : 선택 System.Nullable

The minutes part of the new date. 

초 유형 : 선택 System.Nullable

The seconds part of the new date. Note that you can specify fractions of a second with this parameter. 
0
List<Contact> t = new List<Contact>(); 

String date="9/9/14 3:00:00 PM" 

var result = t.Where(m => m.creationDate == DateTime.ParseExact(date,"M/d/yy h:mm:ss tt",null)); 
+0

문자열이 유효한 DateTime으로 인식되지 않습니다. 오류가 발생합니다. – DonetDeveloper

0

시도는 부분으로 날짜를 분할합니다.

string dt = "9/9/14 3:00:00 PM"; 
var date = DateTime.ParseExact(dt,"M/d/yy h:mm:ss tt",null); 

var q from u in db.Contacts 
     .Where (u.creationDate.DateTime.Year <= date.Year 
        && u.creationDate.DateTime.Month <= date.Month 
        && u.creationDate.DateTime.Day <= date.Day 
        && u.creationDate.DateTime.Day <= date.Hour 
        && u.creationDate.DateTime.Day <= date.Minute 
        && u.creationDate.DateTime.Day <= date.Second 
        ) 
     select u; 
0

당신은

var result = t.Where(m => m.creationDate == DateTime.ParseExact(date,"yyyy/MM/dd HH:mm:ss tt",null)); 

SQL 서버에 저장된 날짜가 YYYY-MM-DD 형식으로되어 사용할 수 있습니다.