Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Entity Framework 4.1 - Code First + WCF 서비스 시 EndpointNotFoundException 오류 - 두 번째 이야기

지난번에 이에 대한 해결책으로 "DbContext.Configuration.ProxyCreationEnabled" 속성을 false 값으로 설정하는 것으로 마무리 지었는데요.

Entity Framework 4.1 - Code First + WCF 서비스 시 EndpointNotFoundException 오류
; https://www.sysnet.pe.kr/2/0/1083

가만 보니, 재현할 수 있는 코드를 싣지 않아서 이번에 다시 그 문제를 살펴보면서 다른 해결책 하나를 더 제시해보려고 합니다.

우선, 서비스 쪽을 만드는 데 간단하게 파일 시스템 기반의 Web Site 프로젝트를 하나 만들고, Entity Framework 4.1 CodeFirst 기능을 테스트 할 수 있도록 "System.Data.Entity" 어셈블리와 4.1버전의 "EntityFramework" 어셈블리를 참조합니다. (EntityFramework.dll의 파일 경로는 대개 다음과 같습니다.)

C:\Program Files (x86)\Microsoft ADO.NET Entity Framework 4.1\Binaries\EntityFramework.dll

개체 정의는 다음과 같이 해주는데,

===== MyEntity.cs =====

public class MyEntity
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Description { get; set; }

    public virtual ICollection<SubEntity> SubEntities { get; set; }
}

public class SubEntity
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Description { get; set; }

    public int MyEntityId { get; set; }
    public virtual MyEntity MyEntity { get; set; }
}

public class DBContext : DbContext
{
    public DBContext() { }

    public DBContext(string connectionString)
        : base(connectionString) { }

    public DbSet MyEntities { get; set; }
    public DbSet SubEntities { get; set; }
}

보는 바와 같이 전형적인 master/slave 형식의 관계이고 DB로는 FK참조가 발생하게 됩니다. 다음으로, 정의된 DBContext 개체가 자연스럽게 연결문자열을 찾을 수 있도록 web.config에 아래와 같이 연결 문자열을 넣어주고,

<connectionStrings>
    <add name="DBContext" providerName="System.Data.SqlClient"
        connectionString="Server=.;Database=EFTestDB;Trusted_Connection=true;"/>
</connectionStrings>

이제 이렇게 구성된 DB를 조작할 수 있는 WCF 서비스를 제공해 줍니다.

===== Service.svc =====

[ServiceContract()]
public interface IMyService
{
    [OperationContract]
    int CreateMyEntity(string description);

    [OperationContract]
    MyEntity[] GetMyEntities();
}

[ServiceBehavior]
public class MyService : IMyService
{
    public int CreateMyEntity(string description)
    {
        using (DBContext db = new DBContext())
        {
            MyEntity myEntity = new MyEntity();
            myEntity.Description = description;
            
            db.MyEntities.Add(myEntity);

            SubEntity subEntity1 = new SubEntity();
            subEntity1.Description = "SubEntity #1";
            subEntity1.MyEntity = myEntity;

            SubEntity subEntity2 = new SubEntity();
            subEntity2.Description = "SubEntity #2";
            subEntity2.MyEntity = myEntity;

            db.SubEntities.Add(subEntity1);
            db.SubEntities.Add(subEntity2);

            db.SaveChanges();

            return myEntity.Id;
        }
    }

    public MyEntity [] GetMyEntities()
    {
        using (DBContext db = new DBContext())
        {
            var items = from record in db.MyEntities
                        select record;

            return items.ToArray();
        }
    }
}

마지막으로 클라이언트 측에서 WSDL 경로를 이용하여 서비스 참조를 쉽게 할 수 있도록 web.config에 system.serviceModel 노드를 다음과 같이 구성해 줍니다.

<system.serviceModel>
    <behaviors>
        <serviceBehaviors>
            <behavior name="">
                <serviceDebug includeExceptionDetailInFaults="true"/>
                <serviceMetadata httpGetEnabled="true"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>




이제 위의 서비스를 테스트 할 수 있는 클라이언트 측 콘솔 응용 프로그램을 하나 만듭니다. 사실, 별다르게 해줄 것은 없고, 서비스 참조만 한 후 Main 코드를 다음과 같이 작성해 주면 됩니다.

class Program
{
    static void Main(string[] args)
    {
        using (ServiceReference1.MyServiceClient svc = new ServiceReference1.MyServiceClient())
        {
            Console.WriteLine(svc.CreateMyEntity("World!"));

            foreach (var item in svc.GetMyEntities())
            {
                Console.WriteLine(item.Description);
            }
        }
    }
}

실행해 보면, CreateMyEntity 메서드 호출은 정상적으로 되지만 GetMyEntities 호출에서는 SubEntities에 대한 DynamicProxies 타입으로 인해 지난번 글에서 살펴본 오류 상황이 발생하게 됩니다.

그런데, 지난번에는 System.ServiceModel.EndpointNotFoundException 예외가 클라이언트에서 발생했었는데, 이번에는 System.ServiceModel.CommunicationException 예외가 발생했습니다.

게다가 WebDev.WebServer40.exe에서는 다음과 같이 예외 메시지가 떨어진 반면,

Unhandled Exception: System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly. at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)


IIS 7.5에서는 예외는 같지만 메시지가 더 많이 출력되는 차이를 보였습니다.

Unhandled Exception: System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://web2008r2.themost2.pe.kr:12000/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---


(비록 예외메시지는 다르지만) 이것으로 재현이 완료되었군요. ^^ 그럼, 이제 이 글의 처음에 이야기한데로 지난 번과 다른 해결책을 제시해야 하는데요. 마침, 이에 대해서 이번달 MSDN Magazine에서 그 해법을 찾을 수 있었습니다.

Demystifying Entity Framework Strategies, Part 3: Classes, Queries and Contexts
; https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/july/msdn-magazine-data-points-demystifying-entity-framework-strategies-part-3-classes-queries-and-contexts

위의 글에 보면, 다음과 같은 설명이 나오는데요.

The second way the EF lets you use POCOs while still benefiting from the framework uses a bit of sleight of hand in the form of proxy objects. If every one of the POCO class properties is marked virtual, the EF runtime will create a proxy (wrapper) around the object and that proxy does the same job as the EntityObject. The proxy class will notify the context of property and relationship changes. You can also leverage the proxies without affecting the entire class. The EF will be able to lazy load navigation properties that are marked virtual, even when the other properties are not.


아시다시피, WCF 서비스로 제공되는 EF 클래스의 인스턴스에는 위에서 설명된 기능들이 전혀 필요가 없습니다. 즉, virtual로 해야 할 이유가 없는데요. 그래서, 다음과 같이 Entity 타입에 대한 정의를 바꿔주면 DbContext.Configuration.ProxyCreationEnabled 속성을 변경하지 않고도 오류 없이 WCF 서비스가 가능합니다.

public class MyEntity
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Description { get; set; }

    public /* virtual */ ICollection<SubEntity> SubEntities { get; set; }
}

public class SubEntity
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Description { get; set; }

    public int MyEntityId { get; set; }
    public /* virtual */ MyEntity MyEntity { get; set; }
}

그런데, 여기서 2가지 방법 중에 어떤 것이 좋을지에 대한 기준이 있어야 하지 않을까요? 제 생각에는 지난번에 살펴 본 DbContext.Configuration.ProxyCreationEnabled 속성을 제어하는 방법이 더 바람직한 방법이라고 봅니다. 왜냐하면, Entity 타입들의 정의가 '사용처'에 따라 바뀌도록 구성한다는 것이 설계상 올바르지 않다고 여겨지기 때문입니다.

그렇게 결론 내릴 거면서 왜 이번 글을 썼냐고 물으시는 분들이 계실 텐데요. ^^ 그래도 중요한 것은 이런 내용을 통해서 EF를 좀 더 이해할 수 있게 되었다는 데 충분한 의미가 있는 거 아닐까요? ^^

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.





뒷 이야기 1 - Entity Framework의 별난 DB 연결 문자열 오류

지정된 DB 연결 문자열로 SQL서버에 접근이 안되는 경우 다음과 같은 예외가 발생할 수 있습니다.

Unhandled Exception: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: The provider did not return a ProviderManifestToken string.

Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
    ...[생략]...

침착하시고 ^^ app.config(또는 web.config)에 지정된 연결 문자열이 올바른지 확인하시면 됩니다.


뒷 이야기 2 - 데이터베이스를 미리 생성해 놓는 경우의 오류

예를 들어, 위의 상황에서 "EFTestDB"라는 데이터베이스를 지정했는데 EF 스스로 생성하도록 하지 않고 만약에 여러분들이 미리 SQL 서버에 해당 이름의 DB를 생성해 놓으면 EF의 기본 동작은 내부 스키마를 검사하지 않고 그 DB를 그대로 재사용하도록 되어 있습니다.

재미있는 것은 이때 클라이언트 측에서 얻게 되는 오류 정보인데 다음과 같이 그 원인을 거의 파악할 수 없는 수준입니다.

Unhandled Exception: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: An error occurred while updating the entries. See the inner exception for details.

Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
    ...[생략]...

더욱 재미있는 것은 ^^ Fiddler로 살펴본 응답 패킷에 더욱 많은 정보가 있다는 점입니다.

HTTP/1.1 500 Internal Server Error
Content-Length: 3837
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 13 Jul 2011 15:09:28 GMT

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode><faultstring xml:lang="ko-KR">An error occurred while updating the entries. See the inner exception for details.</faultstring><detail><ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><HelpLink i:nil="true"/><InnerException><HelpLink i:nil="true"/><InnerException><HelpLink i:nil="true"/><InnerException i:nil="true"/><Message>Invalid object name 'dbo.MyEntities'.</Message><StackTrace> at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)&#xD; at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()&#xD;
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)&#xD;
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()&#xD;
at System.Data.SqlClient.SqlDataReader.get_MetaData()&#xD;
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)&#xD;
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)&#xD;
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)&#xD;
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)&#xD;
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)&#xD;
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)&#xD;
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)&#xD;
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)</StackTrace><Type>System.Data.SqlClient.SqlException</Type></InnerException><Message>An error occurred while updating the entries. See the inner exception for details.</Message><StackTrace> at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)&#xD;
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)&#xD;
at System.Data.Entity.Internal.InternalContext.SaveChanges()</StackTrace><Type>System.Data.UpdateException</Type></InnerException><Message>An error occurred while updating the entries. See the inner exception for details.</Message><StackTrace> at System.Data.Entity.Internal.InternalContext.SaveChanges()&#xD; at MyService.CreateMyEntity(String description) in d:\testWebApp\App_Code\Service.cs:line 44&#xD;
at SyncInvokeCreateMyEntity(Object , Object[] , Object[] )&#xD;
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)&#xD;
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)&#xD;
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)&#xD;
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)&#xD;
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.Data.Entity.Infrastructure.DbUpdateException</Type></ExceptionDetail></detail></s:Fault></s:Body></s:Envelope>


그러니, 저처럼 미리 DB를 생성해 두어서 헤매지 마십시오. ^^ 아니면, DropCreateDatabaseIfModelChanges 같은 DB 초기화 옵션을 사용하는 방법이 있습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 136  137  138  139  140  141  142  143  [144]  145  146  147  148  149  150  ...
NoWriterDateCnt.TitleFile(s)
1454정성태5/31/201326228Java: 15. Java 7 Control Panel 실행시키는 방법
1453정성태5/22/201325241기타: 32. Microsoft FTP 사이트에 접속하는 방법
1452정성태5/21/201332954Windows: 73. TabProcGrowth 값 삭제 후 IE를 실행시키면 다시 복원되는 경우 [3]
1451정성태5/17/201331886Windows: 72. 윈도우 서버 2012 기초 사용법
1450정성태5/16/201322705오류 유형: 176. SQL10007N Message "0" could not be retrieved. Reason code: "3"
1449정성태5/15/201329825오류 유형: 175. SpeechRecognitionEngine 사용 시 오류 유형 2가지
1448정성태5/14/201324806VC++: 68. #pragma warning(disable: ...)로 오류 제어가 안된다면?
1447정성태5/3/201326468개발 환경 구성: 191. Debugging Tools for Windows 독립 설치 버전 [1]
1446정성태4/30/201327242.NET Framework: 368. Encoding 타입의 대체(fallback) 메카니즘 [1]
1445정성태4/26/201325456디버깅 기술: 54. NT 서비스의 Main 메서드 안에서 Process.GetProcessesByName 호출 시 멈춤 현상 [1]
1444정성태4/26/201329489기타: 31. Internet Explorer: 자바스크립트로 숨겨진 파일 다운로드 경로를 알아내는 방법 [1]
1443정성태4/24/201325148개발 환경 구성: 190. Azure PaaS 웹 응용 프로그램 배포 후 SMTP 서버 구성 [2]
1442정성태4/21/201328736기타: 30. 마이크로소프트 워드의 CPU 점유 현상으로 글자 입력이 느려졌다면? [1]
1441정성태4/21/201335339.NET Framework: 367. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 [14]
1440정성태4/19/201324067오류 유형: 174. dumpbin.exe 실행시 mspdb110.dll 로드 오류
1439정성태4/18/201327923VS.NET IDE: 76. Visual Studio 2012와 Itanium 빌드 옵션 [2]
1438정성태4/17/201327311.NET Framework: 366. 다른 프로세스에 환경 변수 설정하는 방법 - 두 번째 이야기 [1]파일 다운로드1
1437정성태4/17/201327540VC++: 67. CRT(C Runtime DLL: msvcr...dll)에 대한 의존성 제거
1436정성태4/17/201332958.NET Framework: 365. Local SYSTEM 권한으로 코드를 실행하는 방법파일 다운로드1
1435정성태4/15/201341843Windows: 71. ad-hoc 보다 더 편리한 "가상 Wifi" 를 이용한 인터넷 공유 [2]
1434정성태4/9/201323120오류 유형: 173. TFS 서버의 이벤트 로그 오류 - WebHost failed to process a request. Parameter name: certificate
1433정성태4/9/201323411개발 환경 구성: 189. TFS에 설치된 SharePoint 의 PowerShell 콘솔 띄우는 방법
1432정성태4/5/201324411오류 유형: 172. System.Web.PipelineModuleStepContainer.GetEventCount 에서 NullReferenceException 이 발생한다면?
1431정성태4/5/201325064기타: 29. 부팅 가능한 (외장) HDD를 기존 부팅 메뉴에 추가하는 방법
1430정성태4/4/201326904제니퍼 .NET: 23. 모바일용 웹 사이트에서 발생하는 응답 시간 지연 현상 [5]파일 다운로드1
1429정성태3/29/201323276개발 환경 구성: 188. SCOM 2012 - ASP.NET 모니터링 방법
... 136  137  138  139  140  141  142  143  [144]  145  146  147  148  149  150  ...