相关疑难解决方法(0)

实体框架6:如何覆盖SQL生成器?

我想在生成数据库模式(DDL)时修改由EF:CF生成的SQL,如实体框架团队建议的那样.

如何才能做到这一点?

我无法通过Google找到合适的内容.

entity-framework sql-generation ef-code-first ef-migrations entity-framework-6

11
推荐指数
1
解决办法
4912
查看次数

Entity Framework 6 Code first 覆盖 MigrationCodeGenerator 的默认值

我发现的所有关于声明默认值的方法都是在 Sql 脚本中生成默认值,而不是在迁移代码中。

我最喜欢的是使用属性:https : //stackoverflow.com/a/34894274/132942

[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }
Run Code Online (Sandbox Code Playgroud)

属性定义

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    public string DefaultValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在上下文的“OnModelCreating”中添加

modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));
Run Code Online (Sandbox Code Playgroud)

然后自定义SqlGenerator。但我不喜欢这样,因为我不知道在生成迁移时是否一切都如我所愿。

为此,我像这样修改了MigrationCodeGeneratorhttps : //stackoverflow.com/a/21024108

在自定义 MigrationCodeGenerator

public class ExtendedMigrationCodeGenerator : MigrationCodeGenerator
{
    public override ScaffoldedMigration Generate(string migrationId, IEnumerable<MigrationOperation> operations, string sourceModel, string targetModel, string @namespace, string className)
    {
        foreach (MigrationOperation …
Run Code Online (Sandbox Code Playgroud)

entity-framework default-value ef-code-first entity-framework-6 entity-framework-migrations

5
推荐指数
1
解决办法
464
查看次数