닷넷 웹 프로그램 디버깅 시작했을 때 나는 DB 객체 오류

안녕하세요. 지난 번에 비주얼스튜디오 세팅 관련해서 질문을 올려서 많은 도움을 받았습니다.
세팅 후 데이터베이스 설정까지 수정한 다음에 디버깅을 눌렀는데 분명 데이터베이스 접속은 되는 것 같은데 객체를 못찾는다는 오류가 나서 어떤식으로 접근을 해야할지 몰라 글을 올립니다.
다시 한번 고수님들의 도움을 받고 싶습니다.
image
보시다시피 객체를 못 찾는다는 오류가 발생하고
데이터베이스를 확인해보면 분명 다음과 같이 있습니다.
image
어느 설정파일을 손을 대면 될까요?
혹시몰라 설정파일 내용 올려봅니다.
image
현재 데이터베이스 이름은 Nudge 로 되어있습니다.
잘 부탁드립니다.

EFCore의 SQL 로깅 기능을 활성화 하신 다음 로그를 통해 실제 연결에 사용되는 Catalog, Schema 등을 면밀히 살펴보시면 문제해결에 도움이 될 듯 합니다.

Logging in Entity Framework Core (entityframeworktutorial.net)

PM> Install-Package Microsoft.Extensions.Logging.Console
    //static LoggerFactory object
    public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
              new ConsoleLoggerProvider((_, __) => true, true)
        });
...
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseLoggerFactory(loggerFactory)  
            .EnableSensitiveDataLogging()  
            .UseSqlServer(@"...");
    }

수정> 아! 네임스페이스를 보고 EF Core인줄 알았는데 타겟이 .NET Framework인걸 보니 Entity Framework 6.0인것 같네요. 아래 코드를 추가해보세요.

using (var db = new NudgeEntities())
{
    db.Database.Log = Console.Write;

    // Your code here...
}

데이터베이스 작업 로깅 및 가로채기 - EF6 | Microsoft Learn
Logging and tracing with Entity Framework 6 (cmatskas.com)

추가> Entity Framework 6의 로그에서는 딱히 유용한 정보가 없을 수도 있습니다.

using (var db = new NudgeEntities())
{
  Console.WriteLine(db.Database.Connection.ConnectionString);
}

위와 같이 ConnectionString도 한번 찍어보세요.

1개의 좋아요

안녕하세요. 댓글 달아주셔서 감사합니다.
말씀하신대로 콘솔로 찍어보니 다음과 같이 나오는데 제가 입력한대로 나옵니다.
혹시 문제되는 부분이 있을까요?
image

공유 주신 ConnectionString이 전체 내용인가요? 데이터베이스가 지정되어 있지 않습니다.

1개의 좋아요

네~ 저게 전체인데요. 원래 저런식으로 기재되어있어서 저게 맞는줄 알았는데 아니었나보네요.
그럼 혹시 뒤에 데이터베이스 지정을 하려면 어떻게 추가를 해야할까요?
정말 그게 맞다면 좋겠네요. 정말 감사합니다.

질문을 주시거나 이러한 유형의 업무상 이슈를 공유하실 때 물론 민감한 패스워드 같은 정보는 가리더라도 될 수 있으면 잘리는 부분 없이 전체의 내용을 알려주시는 것이 빠른 피드백에 유리할 것 같습니다.

  • 줄 바꿈을 설정해서 App.config 파일의 전체 내용
  • 출력 된 ConnectionString의 전문
  • 데이터베이스 트리 캡쳐의 전체 부분 (Server - Database - Table)

그리고 NudgeEntities 클래스가 정의된 프로젝트 상의 파일 구조(NudgeEntities.Context.tt 등)와 클래스의 정의로 이동해서 생성자 부분의 코드도 공유해주시면 좋을 것 같습니다.
Database First 방식으로 NudgeEntities클래스가 생성된 것으로 추측되는데 ConnectionString을 재설정하기 위한 생성자 override가 있는지 확인하기 위함입니다. (이것도 부분적인 정보보다 전체 내용)

2개의 좋아요

아 네 잘 알겠습니다. 그럼 다시 한번 전체내용 공유해서 질문 올리겠습니다.
여러가지로 도움 주셔서 진심으로 감사드립니다.

  1. App.config 전체내용 - 비번만 ***** 처리했습니다.
<?xml version="1.0" encoding="utf-8"?>
  1. 출력된 ConnectionString 전문

  1. 데이터베이스 트리 캡처 전체 - 테이블이 꽤 많습니다. 양해부탁드리겠습니다.
    image

  2. 마지막으로 프로젝트 상의 파일구조를 말씀드리기 위해 전체적인 구조도 함께 말씀드리겠습니다.
    image
    전체 프로젝트는 위 이미지와 같이 되어있고 저는 TestConsole 을 디버깅을 하였습니다.
    처음 프로젝트 관련해서 질문을 올린 적이 있었는데 저걸 디버깅을 해야지 나머지도 함께 구동이 된다고 해서…
    하였더니 다음 파일에서 오류가 난 상태입니다.
    image
    말씀하신 것처럼 NudgeEntities 구조를 보기 위해 ctrl 누른채로 해당 객체로 이동을 했더니
    image
    이 파일로 이동이 되어 해당 파일이 있는 폴더의 구조를 함께 올리겠습니다.
    image

말씀하신 DB.tt, DB.Context.tt 파일을 첨부하려했더니 안되서 전체내용을 붙여넣겠습니다.

  1. DB.tt

<#@ template language=“C#” debug=“false” hostspecific=“true”#>
<#@ include file=“EF6.Utility.CS.ttinclude”#><#@
output extension=“.cs”#><#

const string inputFile = @“DB.edmx”;
var textTransform = DynamicTextTransformation.Create(this);
var code = new CodeGenerationTools(this);
var ef = new MetadataTools(this);
var typeMapper = new TypeMapper(code, ef, textTransform.Errors);
var fileManager = EntityFrameworkTemplateFileManager.Create(this);
var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile);
var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef);

if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile))
{
return string.Empty;
}

WriteHeader(codeStringGenerator, fileManager);

foreach (var entity in typeMapper.GetItemsToGenerate(itemCollection))
{
fileManager.StartNewFile(entity.Name + “.cs”);
BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
<#=codeStringGenerator.EntityClassOpening(entity)#>
{
<#
var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity);
var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity);
var complexProperties = typeMapper.GetComplexProperties(entity);

if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
{

#>
public <#=code.Escape(entity)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}

    foreach (var navigationProperty in collectionNavigationProperties)
    {

#>
this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
<#
}

    foreach (var complexProperty in complexProperties)
    {

#>
this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
}

<#
}

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    foreach (var edmProperty in simpleProperties)
    {

#>
<#=codeStringGenerator.Property(edmProperty)#>
<#
}
}

if (complexProperties.Any())
{

#>

<#
foreach(var complexProperty in complexProperties)
{
#>
<#=codeStringGenerator.Property(complexProperty)#>
<#
}
}

var navigationProperties = typeMapper.GetNavigationProperties(entity);
if (navigationProperties.Any())
{

#>

<#
foreach (var navigationProperty in navigationProperties)
{
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
}
}
#>
}
<#
EndNamespace(code);
}

foreach (var complex in typeMapper.GetItemsToGenerate(itemCollection))
{
fileManager.StartNewFile(complex.Name + “.cs”);
BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#>
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#>
{
<#
var complexProperties = typeMapper.GetComplexProperties(complex);
var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex);

if (propertiesWithDefaultValues.Any() || complexProperties.Any())
{

#>
public <#=code.Escape(complex)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}

    foreach (var complexProperty in complexProperties)
    {

#>
this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
}

<#
}

var simpleProperties = typeMapper.GetSimpleProperties(complex);
if (simpleProperties.Any())
{
    foreach(var edmProperty in simpleProperties)
    {

#>
<#=codeStringGenerator.Property(edmProperty)#>
<#
}
}

if (complexProperties.Any())
{

#>

<#
foreach(var edmProperty in complexProperties)
{
#>
<#=codeStringGenerator.Property(edmProperty)#>
<#
}
}
#>
}
<#
EndNamespace(code);
}

foreach (var enumType in typeMapper.GetEnumItemsToGenerate(itemCollection))
{
fileManager.StartNewFile(enumType.Name + “.cs”);
BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#>
<#
if (typeMapper.EnumIsFlags(enumType))
{
#>
[Flags]
<#
}
#>
<#=codeStringGenerator.EnumOpening(enumType)#>
{
<#
var foundOne = false;

foreach (MetadataItem member in typeMapper.GetEnumMembers(enumType))
{
    foundOne = true;

#>
<#=code.Escape(typeMapper.GetEnumMemberName(member))#> = <#=typeMapper.GetEnumMemberValue(member)#>,
<#
}

if (foundOne)
{
    this.GenerationEnvironment.Remove(this.GenerationEnvironment.Length - 3, 1);
}

#>
}
<#
EndNamespace(code);
}

fileManager.Process();

#>
<#+

public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager)
{
fileManager.StartHeader();
#>
//------------------------------------------------------------------------------
//
// <#=CodeGenerationTools.GetResourceString(“Template_GeneratedCodeCommentLine1”)#>
//
// <#=CodeGenerationTools.GetResourceString(“Template_GeneratedCodeCommentLine2”)#>
// <#=CodeGenerationTools.GetResourceString(“Template_GeneratedCodeCommentLine3”)#>
//
//------------------------------------------------------------------------------
<#=codeStringGenerator.UsingDirectives(inHeader: true)#>
<#+
fileManager.EndBlock();
}

public void BeginNamespace(CodeGenerationTools code)
{
var codeNamespace = code.VsNamespaceSuggestion();
if (!String.IsNullOrEmpty(codeNamespace))
{
#>
namespace <#=code.EscapeNamespace(codeNamespace)#>
{
<#+
PushIndent(" ");
}
}

public void EndNamespace(CodeGenerationTools code)
{
if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion()))
{
PopIndent();
#>
}
<#+
}
}

public const string TemplateId = “CSharp_DbContext_Types_EF6”;

public class CodeStringGenerator
{
private readonly CodeGenerationTools _code;
private readonly TypeMapper _typeMapper;
private readonly MetadataTools _ef;

public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef)
{
    ArgumentNotNull(code, "code");
    ArgumentNotNull(typeMapper, "typeMapper");
    ArgumentNotNull(ef, "ef");

    _code = code;
    _typeMapper = typeMapper;
    _ef = ef;
}

public string Property(EdmProperty edmProperty)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2} {{ {3}get; {4}set; }}",
        Accessibility.ForProperty(edmProperty),
        _typeMapper.GetTypeName(edmProperty.TypeUsage),
        _code.Escape(edmProperty),
        _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
        _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}

public string NavigationProperty(NavigationProperty navProp)
{
    var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType());
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2} {{ {3}get; {4}set; }}",
        AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)),
        navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
        _code.Escape(navProp),
        _code.SpaceAfter(Accessibility.ForGetter(navProp)),
        _code.SpaceAfter(Accessibility.ForSetter(navProp)));
}

public string AccessibilityAndVirtual(string accessibility)
{
    return accessibility + (accessibility != "private" ? " virtual" : "");
}

public string EntityClassOpening(EntityType entity)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1}partial class {2}{3}",
        Accessibility.ForType(entity),
        _code.SpaceAfter(_code.AbstractOption(entity)),
        _code.Escape(entity),
        _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
}

public string EnumOpening(SimpleType enumType)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} enum {1} : {2}",
        Accessibility.ForType(enumType),
        _code.Escape(enumType),
        _code.Escape(_typeMapper.UnderlyingClrType(enumType)));
    }

public void WriteFunctionParameters(EdmFunction edmFunction, Action<string, string, string, string> writeParameter)
{
    var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
    foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
    {
        var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
        var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")";
        var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))";
        writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
    }
}

public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} IQueryable<{1}> {2}({3})",
        AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
        _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
        _code.Escape(edmFunction),
        string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()));
}

public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    
    return string.Format(
        CultureInfo.InvariantCulture,
        "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
        _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
        edmFunction.NamespaceName,
        edmFunction.Name,
        string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()),
        _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
}

public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    var returnType = _typeMapper.GetReturnType(edmFunction);

    var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray());
    if (includeMergeOption)
    {
        paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption";
    }

    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2}({3})",
        AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
        returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
        _code.Escape(edmFunction),
        paramList);
}

public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    var returnType = _typeMapper.GetReturnType(edmFunction);

    var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()));
    if (includeMergeOption)
    {
        callParams = ", mergeOption" + callParams;
    }
    
    return string.Format(
        CultureInfo.InvariantCulture,
        "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});",
        returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
        edmFunction.Name,
        callParams);
}

public string DbSet(EntitySet entitySet)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} virtual DbSet<{1}> {2} {{ get; set; }}",
        Accessibility.ForReadOnlyProperty(entitySet),
        _typeMapper.GetTypeName(entitySet.ElementType),
        _code.Escape(entitySet));
}

public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
    return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
        ? string.Format(
            CultureInfo.InvariantCulture,
            "{0}using System;{1}" +
            "{2}",
            inHeader ? Environment.NewLine : "",
            includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
            inHeader ? "" : Environment.NewLine)
        : "";
}

}

public class TypeMapper
{
private const string ExternalTypeNameAttributeName = @“http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName”;

private readonly System.Collections.IList _errors;
private readonly CodeGenerationTools _code;
private readonly MetadataTools _ef;

public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors)
{
    ArgumentNotNull(code, "code");
    ArgumentNotNull(ef, "ef");
    ArgumentNotNull(errors, "errors");

    _code = code;
    _ef = ef;
    _errors = errors;
}

public static string FixNamespaces(string typeName)
{
    return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial.");
}

public string GetTypeName(TypeUsage typeUsage)
{
    return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
}

public string GetTypeName(EdmType edmType)
{
    return GetTypeName(edmType, isNullable: null, modelNamespace: null);
}

public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
{
    return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
}

public string GetTypeName(EdmType edmType, string modelNamespace)
{
    return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
}

public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
{
    if (edmType == null)
    {
        return null;
    }

    var collectionType = edmType as CollectionType;
    if (collectionType != null)
    {
        return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
    }

    var typeName = _code.Escape(edmType.MetadataProperties
                            .Where(p => p.Name == ExternalTypeNameAttributeName)
                            .Select(p => (string)p.Value)
                            .FirstOrDefault())
        ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
            _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
            _code.Escape(edmType));

    if (edmType is StructuralType)
    {
        return typeName;
    }

    if (edmType is SimpleType)
    {
        var clrType = UnderlyingClrType(edmType);
        if (!IsEnumType(edmType))
        {
            typeName = _code.Escape(clrType);
        }

        typeName = FixNamespaces(typeName);

        return clrType.IsValueType && isNullable == true ?
            String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
            typeName;
    }

    throw new ArgumentException("edmType");
}

public Type UnderlyingClrType(EdmType edmType)
{
    ArgumentNotNull(edmType, "edmType");

    var primitiveType = edmType as PrimitiveType;
    if (primitiveType != null)
    {
        return primitiveType.ClrEquivalentType;
    }

    if (IsEnumType(edmType))
    {
        return GetEnumUnderlyingType(edmType).ClrEquivalentType;
    }

    return typeof(object);
}

public object GetEnumMemberValue(MetadataItem enumMember)
{
    ArgumentNotNull(enumMember, "enumMember");
    
    var valueProperty = enumMember.GetType().GetProperty("Value");
    return valueProperty == null ? null : valueProperty.GetValue(enumMember, null);
}

public string GetEnumMemberName(MetadataItem enumMember)
{
    ArgumentNotNull(enumMember, "enumMember");
    
    var nameProperty = enumMember.GetType().GetProperty("Name");
    return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null);
}

public System.Collections.IEnumerable GetEnumMembers(EdmType enumType)
{
    ArgumentNotNull(enumType, "enumType");

    var membersProperty = enumType.GetType().GetProperty("Members");
    return membersProperty != null 
        ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null)
        : Enumerable.Empty<MetadataItem>();
}

public bool EnumIsFlags(EdmType enumType)
{
    ArgumentNotNull(enumType, "enumType");
    
    var isFlagsProperty = enumType.GetType().GetProperty("IsFlags");
    return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null);
}

public bool IsEnumType(GlobalItem edmType)
{
    ArgumentNotNull(edmType, "edmType");

    return edmType.GetType().Name == "EnumType";
}

public PrimitiveType GetEnumUnderlyingType(EdmType enumType)
{
    ArgumentNotNull(enumType, "enumType");

    return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null);
}

public string CreateLiteral(object value)
{
    if (value == null || value.GetType() != typeof(TimeSpan))
    {
        return _code.CreateLiteral(value);
    }

    return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks);
}

public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
{
    ArgumentNotNull(types, "types");
    ArgumentNotNull(sourceFile, "sourceFile");
    
    var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
    if (types.Any(item => !hash.Add(item)))
    {
        _errors.Add(
            new CompilerError(sourceFile, -1, -1, "6023",
                String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict"))));
        return false;
    }
    return true;
}

public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection)
{
    return GetItemsToGenerate<SimpleType>(itemCollection)
        .Where(e => IsEnumType(e));
}

public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType
{
    return itemCollection
        .OfType<T>()
        .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName))
        .OrderBy(i => i.Name);
}

public IEnumerable<string> GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection)
{
    return itemCollection
        .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i))
        .Select(g => GetGlobalItemName(g));
}

public string GetGlobalItemName(GlobalItem item)
{
    if (item is EdmType)
    {
        return ((EdmType)item).Name;
    }
    else
    {
        return ((EntityContainer)item).Name;
    }
}

public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetComplexProperties(EntityType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
}

public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
}

public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type)
{
    return type.NavigationProperties.Where(np => np.DeclaringType == type);
}

public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type)
{
    return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
}

public FunctionParameter GetReturnParameter(EdmFunction edmFunction)
{
    ArgumentNotNull(edmFunction, "edmFunction");

    var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters");
    return returnParamsProperty == null
        ? edmFunction.ReturnParameter
        : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault();
}

public bool IsComposable(EdmFunction edmFunction)
{
    ArgumentNotNull(edmFunction, "edmFunction");

    var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute");
    return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null);
}

public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction)
{
    return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
}

public TypeUsage GetReturnType(EdmFunction edmFunction)
{
    var returnParam = GetReturnParameter(edmFunction);
    return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage);
}

public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption)
{
    var returnType = GetReturnType(edmFunction);
    return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;
}

}

public static void ArgumentNotNull(T arg, string name) where T : class
{
if (arg == null)
{
throw new ArgumentNullException(name);
}
}
#>

  1. DB.Context.tt

<#@ template language=“C#” debug=“false” hostspecific=“true”#>
<#@ include file=“EF6.Utility.CS.ttinclude”#><#@
output extension=“.cs”#><#

const string inputFile = @“DB.edmx”;
var textTransform = DynamicTextTransformation.Create(this);
var code = new CodeGenerationTools(this);
var ef = new MetadataTools(this);
var typeMapper = new TypeMapper(code, ef, textTransform.Errors);
var loader = new EdmMetadataLoader(textTransform.Host, textTransform.Errors);
var itemCollection = loader.CreateEdmItemCollection(inputFile);
var modelNamespace = loader.GetModelNamespace(inputFile);
var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef);

var container = itemCollection.OfType().FirstOrDefault();
if (container == null)
{
return string.Empty;
}
#>
//------------------------------------------------------------------------------
//
// <#=CodeGenerationTools.GetResourceString(“Template_GeneratedCodeCommentLine1”)#>
//
// <#=CodeGenerationTools.GetResourceString(“Template_GeneratedCodeCommentLine2”)#>
// <#=CodeGenerationTools.GetResourceString(“Template_GeneratedCodeCommentLine3”)#>
//
//------------------------------------------------------------------------------

<#

var codeNamespace = code.VsNamespaceSuggestion();
if (!String.IsNullOrEmpty(codeNamespace))
{
#>
namespace <#=code.EscapeNamespace(codeNamespace)#>
{
<#
PushIndent(" ");
}

#>
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
<#
if (container.FunctionImports.Any())
{
#>
using System.Data.Entity.Core.Objects;
using System.Linq;
<#
}
#>

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
public <#=code.Escape(container)#>()
: base(“name=<#=container.Name#>”)
{
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoadingEnabled = false;
<#
}

foreach (var entitySet in container.BaseEntitySets.OfType())
{
// Note: the DbSet members are defined below such that the getter and
// setter always have the same accessibility as the DbSet definition
if (Accessibility.ForReadOnlyProperty(entitySet) != “public”)
{
#>
<#=codeStringGenerator.DbSetInitializer(entitySet)#>
<#
}
}
#>
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}

<#
foreach (var entitySet in container.BaseEntitySets.OfType())
{
#>
<#=codeStringGenerator.DbSet(entitySet)#>
<#
}

foreach (var edmFunction in container.FunctionImports)
{
    WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: false);
}

#>
}
<#

if (!String.IsNullOrEmpty(codeNamespace))
{
PopIndent();
#>
}
<#
}
#>
<#+

private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
{
if (typeMapper.IsComposable(edmFunction))
{
#>

[DbFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")]
<#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#>
{

<#+
codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter);
#>
<#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#>
}
<#+
}
else
{
#>

<#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#>
{

<#+
codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter);
#>
<#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#>
}
<#+
if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption))
{
WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true);
}
}
}

public void WriteFunctionParameter(string name, string isNotNull, string notNullInit, string nullInit)
{
#>
var <#=name#> = <#=isNotNull#> ?
<#=notNullInit#> :
<#=nullInit#>;

<#+
}

public const string TemplateId = “CSharp_DbContext_Context_EF6”;

public class CodeStringGenerator
{
private readonly CodeGenerationTools _code;
private readonly TypeMapper _typeMapper;
private readonly MetadataTools _ef;

public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef)
{
    ArgumentNotNull(code, "code");
    ArgumentNotNull(typeMapper, "typeMapper");
    ArgumentNotNull(ef, "ef");

    _code = code;
    _typeMapper = typeMapper;
    _ef = ef;
}

public string Property(EdmProperty edmProperty)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2} {{ {3}get; {4}set; }}",
        Accessibility.ForProperty(edmProperty),
        _typeMapper.GetTypeName(edmProperty.TypeUsage),
        _code.Escape(edmProperty),
        _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
        _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}

public string NavigationProperty(NavigationProperty navProp)
{
    var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType());
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2} {{ {3}get; {4}set; }}",
        AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)),
        navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
        _code.Escape(navProp),
        _code.SpaceAfter(Accessibility.ForGetter(navProp)),
        _code.SpaceAfter(Accessibility.ForSetter(navProp)));
}

public string AccessibilityAndVirtual(string accessibility)
{
    return accessibility + (accessibility != "private" ? " virtual" : "");
}

public string EntityClassOpening(EntityType entity)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1}partial class {2}{3}",
        Accessibility.ForType(entity),
        _code.SpaceAfter(_code.AbstractOption(entity)),
        _code.Escape(entity),
        _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
}

public string EnumOpening(SimpleType enumType)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} enum {1} : {2}",
        Accessibility.ForType(enumType),
        _code.Escape(enumType),
        _code.Escape(_typeMapper.UnderlyingClrType(enumType)));
    }

public void WriteFunctionParameters(EdmFunction edmFunction, Action<string, string, string, string> writeParameter)
{
    var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
    foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
    {
        var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
        var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")";
        var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))";
        writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
    }
}

public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} IQueryable<{1}> {2}({3})",
        AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
        _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
        _code.Escape(edmFunction),
        string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()));
}

public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    
    return string.Format(
        CultureInfo.InvariantCulture,
        "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
        _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
        edmFunction.NamespaceName,
        edmFunction.Name,
        string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()),
        _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
}

public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    var returnType = _typeMapper.GetReturnType(edmFunction);

    var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray());
    if (includeMergeOption)
    {
        paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption";
    }

    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2}({3})",
        AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
        returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
        _code.Escape(edmFunction),
        paramList);
}

public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    var returnType = _typeMapper.GetReturnType(edmFunction);

    var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()));
    if (includeMergeOption)
    {
        callParams = ", mergeOption" + callParams;
    }
    
    return string.Format(
        CultureInfo.InvariantCulture,
        "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});",
        returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
        edmFunction.Name,
        callParams);
}

public string DbSet(EntitySet entitySet)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} virtual DbSet<{1}> {2} {{ get; set; }}",
        Accessibility.ForReadOnlyProperty(entitySet),
        _typeMapper.GetTypeName(entitySet.ElementType),
        _code.Escape(entitySet));
}

public string DbSetInitializer(EntitySet entitySet)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} = Set<{1}>();",
        _code.Escape(entitySet),
        _typeMapper.GetTypeName(entitySet.ElementType));
}

public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
    return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
        ? string.Format(
            CultureInfo.InvariantCulture,
            "{0}using System;{1}" +
            "{2}",
            inHeader ? Environment.NewLine : "",
            includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
            inHeader ? "" : Environment.NewLine)
        : "";
}

}

public class TypeMapper
{
private const string ExternalTypeNameAttributeName = @“http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName”;

private readonly System.Collections.IList _errors;
private readonly CodeGenerationTools _code;
private readonly MetadataTools _ef;

public static string FixNamespaces(string typeName)
{
    return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial.");
}

public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors)
{
    ArgumentNotNull(code, "code");
    ArgumentNotNull(ef, "ef");
    ArgumentNotNull(errors, "errors");

    _code = code;
    _ef = ef;
    _errors = errors;
}

public string GetTypeName(TypeUsage typeUsage)
{
    return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
}

public string GetTypeName(EdmType edmType)
{
    return GetTypeName(edmType, isNullable: null, modelNamespace: null);
}

public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
{
    return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
}

public string GetTypeName(EdmType edmType, string modelNamespace)
{
    return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
}

public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
{
    if (edmType == null)
    {
        return null;
    }

    var collectionType = edmType as CollectionType;
    if (collectionType != null)
    {
        return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
    }

    var typeName = _code.Escape(edmType.MetadataProperties
                            .Where(p => p.Name == ExternalTypeNameAttributeName)
                            .Select(p => (string)p.Value)
                            .FirstOrDefault())
        ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
            _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
            _code.Escape(edmType));

    if (edmType is StructuralType)
    {
        return typeName;
    }

    if (edmType is SimpleType)
    {
        var clrType = UnderlyingClrType(edmType);
        if (!IsEnumType(edmType))
        {
            typeName = _code.Escape(clrType);
        }

        typeName = FixNamespaces(typeName);

        return clrType.IsValueType && isNullable == true ?
            String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
            typeName;
    }

    throw new ArgumentException("edmType");
}

public Type UnderlyingClrType(EdmType edmType)
{
    ArgumentNotNull(edmType, "edmType");

    var primitiveType = edmType as PrimitiveType;
    if (primitiveType != null)
    {
        return primitiveType.ClrEquivalentType;
    }

    if (IsEnumType(edmType))
    {
        return GetEnumUnderlyingType(edmType).ClrEquivalentType;
    }

    return typeof(object);
}

public object GetEnumMemberValue(MetadataItem enumMember)
{
    ArgumentNotNull(enumMember, "enumMember");
    
    var valueProperty = enumMember.GetType().GetProperty("Value");
    return valueProperty == null ? null : valueProperty.GetValue(enumMember, null);
}

public string GetEnumMemberName(MetadataItem enumMember)
{
    ArgumentNotNull(enumMember, "enumMember");
    
    var nameProperty = enumMember.GetType().GetProperty("Name");
    return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null);
}

public System.Collections.IEnumerable GetEnumMembers(EdmType enumType)
{
    ArgumentNotNull(enumType, "enumType");

    var membersProperty = enumType.GetType().GetProperty("Members");
    return membersProperty != null 
        ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null)
        : Enumerable.Empty<MetadataItem>();
}

public bool EnumIsFlags(EdmType enumType)
{
    ArgumentNotNull(enumType, "enumType");
    
    var isFlagsProperty = enumType.GetType().GetProperty("IsFlags");
    return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null);
}

public bool IsEnumType(GlobalItem edmType)
{
    ArgumentNotNull(edmType, "edmType");

    return edmType.GetType().Name == "EnumType";
}

public PrimitiveType GetEnumUnderlyingType(EdmType enumType)
{
    ArgumentNotNull(enumType, "enumType");

    return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null);
}

public string CreateLiteral(object value)
{
    if (value == null || value.GetType() != typeof(TimeSpan))
    {
        return _code.CreateLiteral(value);
    }

    return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks);
}

public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
{
    ArgumentNotNull(types, "types");
    ArgumentNotNull(sourceFile, "sourceFile");
    
    var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
    if (types.Any(item => !hash.Add(item)))
    {
        _errors.Add(
            new CompilerError(sourceFile, -1, -1, "6023",
                String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict"))));
        return false;
    }
    return true;
}

public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection)
{
    return GetItemsToGenerate<SimpleType>(itemCollection)
        .Where(e => IsEnumType(e));
}

public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType
{
    return itemCollection
        .OfType<T>()
        .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName))
        .OrderBy(i => i.Name);
}

public IEnumerable<string> GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection)
{
    return itemCollection
        .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i))
        .Select(g => GetGlobalItemName(g));
}

public string GetGlobalItemName(GlobalItem item)
{
    if (item is EdmType)
    {
        return ((EdmType)item).Name;
    }
    else
    {
        return ((EntityContainer)item).Name;
    }
}

public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetComplexProperties(EntityType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
}

public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
}

public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type)
{
    return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
}

public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type)
{
    return type.NavigationProperties.Where(np => np.DeclaringType == type);
}

public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type)
{
    return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
}

public FunctionParameter GetReturnParameter(EdmFunction edmFunction)
{
    ArgumentNotNull(edmFunction, "edmFunction");

    var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters");
    return returnParamsProperty == null
        ? edmFunction.ReturnParameter
        : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault();
}

public bool IsComposable(EdmFunction edmFunction)
{
    ArgumentNotNull(edmFunction, "edmFunction");

    var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute");
    return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null);
}

public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction)
{
    return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
}

public TypeUsage GetReturnType(EdmFunction edmFunction)
{
    var returnParam = GetReturnParameter(edmFunction);
    return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage);
}

public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption)
{
    var returnType = GetReturnType(edmFunction);
    return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;
}

}

public static void ArgumentNotNull(T arg, string name) where T : class
{
if (arg == null)
{
throw new ArgumentNullException(name);
}
}
#>

바쁘신데 친절히 답변해주셔서 진심으로 감사드립니다~^^

고생하셨습니다ㅎ

이 부분 한번만 다시 부탁드립니다.

@dimohy 님 말씀대로 현재 접근하는 ConnectionString에 데이터베이스 이름(Initial Catalog)가 설정되지 않은 것으로 보이는데 이 ConnectionString이 App.config의 어떤 부분에서 정의되어 있는지 확인이 필요합니다.

1개의 좋아요

SQL Server Profiler 라는 유용한 도구를 함께 제공 합니다.
이번참에 한번 사용해 보셔요.

NudgeEntities로 보이고
뒤에 화면에 짤려 보에는 커넥션스트링이 연결 정보로 보입니다.

1개의 좋아요

이제 대강의 유곽이 나온듯 합니다.
App.config 파일 내 NudgeEntities를 보시면

<add name="NudgeEntities"... provider connectionstring=&quote;data source=localhost,1433;

부분의 data source=localhost,1433;뒤에 Database 이름을 지정하는 initial catalog= 부분이 누락되어 있을겁니다. initial catalog=Nudge;를 추가해 보십시오,
단, Biz 폴더와 TestConsole 쪽 두 군데에 존재할건데 아마 TestConsole 쪽을 수정하셔야 할 것 같고 안된다면 TestConsole\bin\Debug 폴더 내 TestConsole.exe.config파일도 확인해 보십시오.

App.config 파일로 설정하는 방법 외에도 DB.Context.tt를 수정하셔서 ConnectionString을 입력으로 받는 NudgeEntities 생성자를 추가하실 수 있습니다.

위 부분의 코드는 public NudgeEntities() : base("name=NudgeEntities")로 상위 생성자를 호출하도록 하는 코드를 생성하는데요,

public static string ConnectionString { get; set; } = "name=<#=container.Name#>";
public <#=code.Escape(container)#>() 
: base(ConnectionString)

이렇게 수정을 하시면

NudgeEntities.ConnectionString = $"Data Source={DatabaseInstance};Initial Catalog={Database};User ID={UserName}; Password='{Password}';";
...

using (var db = new NudgeEntities()) 
{
   ...
}

위과 같은 형식으로 코드에서 직접 ConnectionString을 지정해서 사용하실 수 있습니다.
DB.Context.tt 파일을 수정 후 저장한 뒤 하위에 있는 DB.Context.cs 파일을 열어서 정상 수정을 확인하실 수 있습니다.

2개의 좋아요

오늘은 다른 업무로 정신이 없어서 아직 해보지 못했는데 정말 진심으로 감사드립니다.
이렇게 다른 사람 소스를 정성껏 검토해서 오류를 찾아주시다니…ㅠㅜ
오늘 밤이나 내일 중으로 말씀하신대로 수정해서 해보겠습니다.
정말정말 감사드립니다. 저대로 수정해서 온전히 돌아가면 좋겠네요.^^

1개의 좋아요

al6uiz 님 댓글로 친절히 달아주신대로 했더니 해당 오류 없이 잘 실행이 되었습니다.
진심으로 감사드립니다.
그런데 오류없이 먼가 싹~ 지나가고 콘솔창이 닫히는걸 보니 먼가 조건에 맞지 않아서 종료처리되고 있더라구요. 대략적으로 코드를 보니 DB 에 있는 값들을 비교해서 있으면 다음을 수행하고 머 그런식이어서 중간에 DB 데이터 값을 넣고 실행했더니 그 부분은 넘어가는데 또 다른 부분에 맞는 조건 데이터가 없어서 종료되고 그러더라구요. 여기까지만 한 것도 정말 많은 발전을 한 것 같습니다.
image

제가 제대로 이해를 하고 있는 건지 모르겠네요. 아래처럼 전체 솔루션탐색기에 여러개 폴더가 있는데
image
프로젝트 세팅 후 실행을 하기 위한 방법을 문의했을 때 TestConsole 을 실행하면 될 것이라해서 지금까지 질문을 드리고 수정을 했는데 TestConsole 실행했을 때 실행되는 코드를 보면 그냥 단순히 포인트 적립에 관한 코드만 있어서 저 부분이 온전히 처리가 되면 전체 웹 프로젝트가 실행이 되는 건지 잘 모르겠습니다.
저는 Web 폴더 하위에 있는 csproj 를 디버깅을 해야 전체 웹이 띄워질 것 같은데 그걸 디버깅을 하면
image

이런 오류가 발생을해서 TestConsole 을 통해서 실행이 되는 것이라 생각했습니다.
제 생각이 틀린거죠? Web.csproj 파일을 디버깅해서 실행하는게 맞겠죠? 그렇다면 저 오류를 처리해야할텐데… 또 난감해지네요. 시간이 괜찮으시면 조금 더 도와주실 수 있을까요?^^