在我的场景中,我想要用下划线作为前缀来
命名所有表名。版本:
Core 2.2。
我不使用
Id
作为主键列的名称,而是将表名与Id相结合,就像这样:
FoodId
。这迫使我向主键添加了
[Key]
数据注释。
模型
示例模型生成:
using System;
using System.Collections.Generic;
namespace MyNamespace
{
public partial class Food
{
public int FoodId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
}
预期结果:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MyNamespace
{
public partial class _Food
{
[Key]
public int FoodId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
}
我是如何解决这个问题的
我结合了@Chris Peacock和@DavidC的答案。
1. 首先,重命名所有实体
为了防止属性被重命名,我必须明确告诉哪些唯一标识符需要重命名,因为Uniquifier
函数不会告诉你它重命名了哪种类型。
public class MyCSharpUtilities : CSharpUtilities
{
public override string Uniquifier(string proposedIdentifier, ICollection<string> existingIdentifiers)
{
var finalIdentifier = base.Uniquifier(proposedIdentifier, existingIdentifiers);
if (finalIdentifier == "Food" ||
finalIdentifier == "Fruit" ||
finalIdentifier == "Vegetables")
{
finalIdentifier = "_" + finalIdentifier;
}
return finalIdentifier;
}
}
2. 其次,添加using
语句和[Key]
public class MyEntityTypeGenerator : CSharpEntityTypeGenerator
{
public MyEntityTypeGenerator(ICSharpHelper cSharpHelper) : base(cSharpHelper) { }
public override string WriteCode(IEntityType entityType, string @namespace, bool useDataAnnotations)
{
string code = base.WriteCode(entityType, @namespace, useDataAnnotations);
string entityTypeName = entityType.Name.Replace("_", "");
string keyPropertyString = "public int " + entityTypeName + "Id { get; set; }";
if (code.Contains(keyPropertyString))
{
string oldString = "using System.Collections.Generic;" + Environment.NewLine + Environment.NewLine + "namespace MyNamespace";
string newString = "using System.Collections.Generic;" + Environment.NewLine + "using System.ComponentModel.DataAnnotations;" + Environment.NewLine + Environment.NewLine + "namespace MyNamespace";
code = code.Replace(oldString, newString);
string newKeyPropertyString = "[Key]" + Environment.NewLine + "\t\t" + keyPropertyString;
code = code.Replace(keyPropertyString, newKeyPropertyString);
}
return code;
}
}
3. 最后,在 Startup.cs 中添加这些服务。
public class CustomEFDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<ICSharpUtilities, MyCSharpUtilities>();
serviceCollection.AddSingleton<ICSharpEntityTypeGenerator, MyEntityTypeGenerator>();
}
}
CSharpEntityTypeGenerator
现在需要ICSharpHelper
。此外,脚手架框架如何知道执行MyDesignTimeServices.ConfigureDesignTimeServices
? - LP13