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

비밀번호

댓글 작성자
 




... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13173정성태11/27/20225754.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225433.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20225134Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225385Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225975Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20225313제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20225331.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20225042개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224900개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225894개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225789개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226836.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20226175.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20226052.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20229337.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225464오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20226111.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20227070.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226548디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20226019.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20227310.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225914.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20226097C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20226028C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20226010오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225947오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...