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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12120정성태1/19/202011173.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)파일 다운로드1
12119정성태1/17/202011205디버깅 기술: 160. Windbg 확장 DLL 만들기 (3) - C#으로 만드는 방법
12118정성태1/17/202011870개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기 [1]
12117정성태1/15/202010868디버깅 기술: 159. C# - 디버깅 중인 프로세스를 강제로 다른 디버거에서 연결하는 방법파일 다운로드1
12116정성태1/15/202011357디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202011090디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202012959디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202013584오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/202010122오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202013421디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202011998디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209894오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209965오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010891.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012385VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010975디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011645DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202014413DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
12102정성태1/6/202011974디버깅 기술: 152. User 권한(Ring 3)의 프로그램에서 _ETHREAD 주소(및 커널 메모리를 읽을 수 있다면 _EPROCESS 주소) 구하는 방법
12101정성태1/5/202011314.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/20209335.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011664디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202011271.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209806디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911775디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201913232VC++: 135. C++ - string_view의 동작 방식
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...