實體框架核心自定義腳手架

c# entity-framework-core

我已經完成了我的SQLServer數據庫的腳手架。它會在指定的文件夾中創建POCO對象。我想做的是它從我的基類擴展。我也使用存儲庫模式,所以我需要在每個實體上都有Id密鑰,而且每次我重新填充數據庫時我都不想改變它。

腳手架模型示例

public partial class Food
{
     public int Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     public double Price { get; set; }
}

預期結果:

public partial class Food : EntityBase
{
     public string Name { get; set; }
     public string Description { get; set; }
     public double Price { get; set; }
}

public class EntityBase : IEntityBase
{
    public int Id { get; set; }
}

一般承認的答案

您可以使用DbContextWriterEntityTypeWriter來自定義腳手架輸出。

在較新版本的實體核心編寫器中重命名:

  • DBContextWriter == >> CSharpDbContextGenerator
  • EntityTypeWriter == >> CSharpEntityTypeGenerator

編寫一些自定義類型編寫器,您可以覆蓋所有內容,您將獲得自己的代碼生成器:

//HERE YOU CAN CHANGE THE WAY TYPES ARE GENERATED AND YOU CAN ADD INTERFACE OR BASE CLASS AS PARENT.
public class CustomEntitiyTypeWriter : EntityTypeWriter
{
    public CustomEntitiyTypeWriter([NotNull] CSharpUtilities cSharpUtilities)
        : base(cSharpUtilities)
    { }

    // Write Code returns generated code for class and you can raplec it with your base class
    public override string WriteCode([NotNull] EntityConfiguration entityConfiguration)
    {
        var classStr = base.WriteCode(entityConfiguration);

        var defaultStr = "public partial class " + entityConfiguration.EntityType.Name;
        var baseStr = "public partial class " + entityConfiguration.EntityType.Name + " : EntityBase";

        classStr = classStr.Replace(defaultStr, baseStr);

        return classStr;
    }      
}

在設置中聲明它:

public static void ConfigureDesignTimeServices(IServiceCollection services)
           => services.AddSingleton<EntityTypeWriter, CustomEntitiyTypeWriter>();

然後使用scaffold db,您可以使用CustomDBContextWriter為DBContext執行相同操作。


熱門答案

@Tornike Choladze的出色答案使我朝著正確的方向前進,但在最新版本的.Net Core(2.0>)中,就設置而言,這似乎有點不同。

自定義實體類型生成器:

class MyEntityTypeGenerator : CSharpEntityTypeGenerator
{
    public MyEntityTypeGenerator(ICSharpUtilities cSharpUtilities) : base(cSharpUtilities) { }

    public override string WriteCode(IEntityType entityType, string @namespace, bool useDataAnnotations)
    {
        string code = base.WriteCode(entityType, @namespace, useDataAnnotations);

        var oldString = "public partial class " + entityType.Name;
        var newString = "public partial class " + entityType.Name + " : EntityBase";

        return code.Replace(oldString, newString);
    }
}

和設置,它由同一個程序 IDesignTimeServices的一個類組成,並實現IDesignTimeServices

public class MyDesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<ICSharpEntityTypeGenerator, MyEntityTypeGenerator>();            
    }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因