如何为继承泛型类BaseTranslation的所有实体配置复合主键?
问题原因与解决方案
核心问题:开放泛型类型的继承判断逻辑错误
你使用IsSubclassOf(typeof(BaseTranslation<,>))筛选实体类型,但这个方法仅在目标类型直接继承自开放泛型类型时才返回true。而你的SerieTranslation实际继承的是封闭泛型BaseTranslation<byte, Serie>,并非开放泛型BaseTranslation<,>,导致筛选条件永远不成立,循环内的主键配置代码根本没有执行。正确的类型筛选与配置代码
需要遍历实体类型的基类链,检查是否继承自目标泛型基类的开放定义:
protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); var baseTranslationOpenType = typeof(BaseTranslation<,>); foreach (var entityType in builder.Model.GetEntityTypes()) { var currentType = entityType.ClrType; // 遍历基类链,排查是否继承自目标泛型基类 while (currentType != null && currentType != typeof(object)) { if (currentType.IsGenericType && currentType.GetGenericTypeDefinition() == baseTranslationOpenType) { builder.Entity(entityType.Name, x => { x.HasKey("EntityId", "LanguageId"); }); break; } currentType = currentType.BaseType; } } }
- 关键细节说明
- 遍历基类链是为了兼容多层继承的场景,避免遗漏间接继承的情况
- 先通过
IsGenericType判断当前基类是否为泛型类型,防止调用GetGenericTypeDefinition()时抛出异常 GetGenericTypeDefinition()用于获取泛型类型的开放定义,再与BaseTranslation<,>做对比,能准确识别所有继承自该泛型基类的封闭泛型子类
内容的提问来源于stack exchange,提问作者ManuelV
相关产品推荐
相关产品推荐

