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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13606정성태4/24/202491닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024327닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024345오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024586닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024797닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024838닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024848닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024862닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024884닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024866닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241052닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241218C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241194닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241263닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241329Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241112Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241062개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241299Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241557Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...