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)
13517정성태1/8/20242221스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242347닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242625닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242318개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242226닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242180개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242200닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242122닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242170오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242243오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242892닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232482닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20233009닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232591닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232451Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232574닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232328개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232422디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233114닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232509오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232505Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232428Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232612Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232755닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232422개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232281Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...