C#POCO T4模板,生成接口?

Jon*_*nna 12 c# entity-framework poco

有谁知道POCO T4模板的任何调整版本,它会产生接口和类?即如果我在.edmx文件中有Movie和Actor实体,我需要获得以下类和接口.

interface IMovie
{
    string MovieName { get; set; }
    ICollection<IActor> Actors { get; set; } //instead of ICollection<Actor>
}

class Movie : IMovie
{
    string MovieName { get; set; }
    ICollection<IActor> Actors { get; set; } //instead of ICollection<Actor>
}

interface IActor
{
    string ActorName { get; set; }
}

class Actor
{
    string ActorName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

另外,为了防止我编写自己的实体,POCO代理(我需要它们用于延迟加载)是否可以使用如上所示的接口声明?

Sco*_*ott 5

您可以编辑生成POCO实体的默认T4模板,以生成接口.我在工作项目上做了一段时间.这个链接涵盖了我们如何做到这一点的主旨.这相对容易.

这是我们的T4模板的片段,可能有所帮助.我们将此代码插入到生成POCO实体的默认T4模板中.

<#
    GenerationEnvironment.Clear();
    string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);    
    string outputPath = Path.Combine(templateDirectory + @"..\..\Models\Interfaces\Repositories\IEntitiesContext.cs");
#>

using System;
using System.Data.Objects;
using Models.DataModels;

namespace Interfaces.Repositories
{
    #pragma warning disable 1591
    public interface IEntitiesContext : IDisposable
    {
    <#
        region.Begin("ObjectSet Properties", 2);

        foreach (EntitySet entitySet in container.BaseEntitySets.OfType<EntitySet>())
        {
#>
        IObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=code.Escape(entitySet)#> { get; }
<#
        }
        region.End();

        region.Begin("Function Imports", 2);

        foreach (EdmFunction edmFunction in container.FunctionImports)
        {
            var parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
            string paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
            if (edmFunction.ReturnParameter == null)
            {
                continue;
            }
            string returnTypeElement = code.Escape(ef.GetElementType(edmFunction.ReturnParameter.TypeUsage));

#>
    ObjectResult<<#=returnTypeElement#>> <#=code.Escape(edmFunction)#>(<#=paramList#>);
<#
        }

        region.End();
#>

        int SaveChanges();
        ObjectContextOptions ContextOptions { get; }
        System.Data.Common.DbConnection Connection { get; }
        ObjectSet<T> CreateObjectSet<T>() where T : class;
    }
    #pragma warning restore 1591
}
<#
        System.IO.File.WriteAllText(outputPath, GenerationEnvironment.ToString());
        GenerationEnvironment.Clear();
#>
Run Code Online (Sandbox Code Playgroud)

  • 这个T4将为上下文生成一个接口,但它似乎不会为实际实体(IMovie,IActor等)生成接口,对吧? (2认同)