EntityFramework - Derive entities from a base class

通过在项目中添加 EF 6.x DbContext 生成器,修改其中的生成模板,可以让所有的表对象继承自同一个对象。下面的示例显示了如何定义一个BaseDbObject,以及关联继承关系

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF6.Utility.CS.ttinclude"#><#@ 
 output extension=".cs"#><#
 
const string inputFile = @"NorthwndDBModel.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);
 
// ----------------------------------

// ---   Create BaseDbObject.cs   ---

// ----------------------------------

fileManager.StartNewFile("BaseDbObject" + ".cs");
BeginNamespace(code);
#>
public class BaseDbObject
{
}
<#
EndNamespace(code);
 
foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
    fileManager.StartNewFile(entity.Name + ".cs");
    BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
<#=codeStringGenerator.EntityClassOpening(entity)#> : BaseDbObject